我正在尝试使用 mat-select 下拉列表中的所有选定值填充一个数组。目标是为每个选定的值创建一个输入字段,如下所示:
我考虑过每次选择一个值时调用一个方法,但我不确定下一步该做什么... 这是我的:
MyComponent.component.html
<mat-form-field>
<mat-select placeholder="Products" [formControl]="products" multiple>
<mat-option *ngFor="let product of productsList">{{ product }}</mat-option>
</mat-select>
</mat-form-field>
MyComponent.component.ts
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'm-mycomponent',
templateUrl: './mycomponent.component.html',
styleUrls: ['./mycomponent.component.scss']
})
export class MyComponent implements OnInit {
products = new FormControl();
productsList = ['Prod1', 'Prod2', 'Prod3', 'Prod4', 'Prod5', 'Prod6'];
productsToReturn = [];
constructor() { }
ngOnInit() {
}
fillProductsToReturn(product){
if(!this.productsToReturn.includes(product)){
this.productsToReturn.push(product);
}
}
}
如何调用 html 文件中的方法并填充 productsToReturn 数组?
谢谢!
最佳答案
您没有指定何时要访问所选对象。
如果您想在提交表单时访问它很简单,就像单击按钮一样。然后您可以使用 this.products.value
来获取选定的选项。
如果你在选择的时候想要它,那么你可以绑定(bind)到selectionChange()
事件
<mat-select placeholder="Products" [formControl]="products" multiple (selectionChange)="onSelectionChange($event) >
然后在ts文件中就可以得到选中的选项
onSelectionChange(e){
console.log(e.value); //or
console.log(this.toppings.value);
}
关于javascript - 如何使用 Angular 下拉列表中的选定值填充数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54944769/