Consider the two different ways to generate a mat-select dropdown display with multiple options from an array (in this case optionList
) in the .ts
file.
something.component.html
<!-- Place the *ngFor in mat-select-->
<mat-form-field>
<mat-label>Dropdown</mat-label>
<mat-select *ngFor="let option of optionList;" [(value)]="selectedOption">
<mat-option [value]="option">
{{option}}
</mat-option>
</mat-select>
</mat-form-field>
<!-- Place the *ngFor in mat-option -->
<mat-form-field>
<mat-label>Dropdown</mat-label>
<mat-select [(value)]="selectedOption">
<mat-option *ngFor="let option of optionList;" [value]="option">
{{option}}
</mat-option>
</mat-select>
</mat-form-field>
Both html-blocks appear to have the exact same functionality. So, is there a better/standard way of doing things? Does one have some advantage over the other?
Thanks
Both HTML blocks appear to have the exact same functionality
No, they do not have the same functionality. The first one repeats the entire select
which will lead to multiple dropdowns within the mat-form-field
. You need only the option
elements to be repeated so the second one is the way to go.
Does one have some advantage over the other?
Well clearly from the above point we can conclude that the second one works and the first one doesn't.
Just plug those HTML blocks into a simple StackBlitz and assign an array to optionList
and you will see that the first one does not work as expected and produces a weird result.
Four select
elements get created since I used optionList
of length 4.
Conclusion
Use the second HTML block and check out the ngFor
docs.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.