Here is the variants
array:
[
{
type: 'color',
options: ['red', 'green', 'blue']
},
{
type: 'size',
options: ['M', 'G', 'GG']
}
]
Firstly, I need to get an array of type
like this types = ['color', 'size']
. Then, I'll use this array inside a mat-select
:
<mat-select placeholder="Types" (selectionChange)="typeChange($event.value)">
<mat-option *ngFor="let type of types" [value]="type"> {{type}} </mat-option>
</mat-select>
Secondly, I need to populate a array of options
by filtering the variants
array to find the correct type:
typeChange(type: string) {
const variant = this.variants.find(v => v.type === type);
this.options = variant.options;
}
Then I can populate the second select
with the options:
<mat-select placeholder="Options">
<mat-option *ngFor="let opt of options" [value]="opt"> {{opt}} </mat-option>
</mat-select>
I need to populate this two mat-selects
using variants
array. Is there a good way to achieve this?
Please correct me if I am wrong, I believe instead of two arrays of variants, there is one array. I have created a sample example on stackblitz . You just have to create types array.
Here is the ts code :
variants = [
{
type: 'color',
options: ['red', 'green', 'blue']
},
{
type: 'size',
options: ['M', 'G', 'GG']
}
]
types = [];
options = [];
ngOnInit(){
this.variants.forEach(t=>this.types.push(t.type));
}
typeChange(type: string) {
const variant = this.variants.find(v => v.type === type);
this.options = variant.options;
}
Please let me know if you have any question.
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.