LINQ in ngFor Angular 6

Asked by At

I get some 15 different lookup list values in the component.ts and i assign each to a list and bind it to the <select> in html. This works fine.

To make this code more in a cleaner way, is there anything like this?

<mat-form-field class="example-full-width">
              <mat-label>Preferred Job</mat-label>
              <mat-select>
                 <mat-option *ngFor="let job of designationList.filter(x=>x.lookupName === 'Designation')" [value]="job.id">
                  {{job.lookupValue}}
                </mat-option> 
              </mat-select>
            </mat-form-field>

Kind of where or filter condition could directly be applied in the <select> so that i can no longer use separate list for each dropdown?

2 Answers

1
nevzatopcu On Best Solutions

You can use custom function for this variable.

component.ts

filteredDesignationList(loopUpName: string){
    return this.designationList.filter(x=>x.lookupName === loopUpName)"
}

component.html

<mat-form-field class="example-full-width">
              <mat-label>Preferred Job</mat-label>
              <mat-select>
                 <mat-option *ngFor="let job of filteredDesignationList('Designation') [value]="job.id">
                  {{job.lookupValue}}
                </mat-option> 
              </mat-select>
            </mat-form-field>
1
Mohammadreza Imani On

Yes, you should use a Pipe to filter your data instead of using the filter directly.

<mat-option *ngFor="let job of designationList|filter-pipe" [value]="job.id">
              {{job.lookupValue}}
</mat-option> 

And take a look at this to learn how to implement a pipe:

https://angular.io/guide/pipes