[英]Make a form and fetch values for non-input fields with Angular Material
我有一個帶有下拉菜單的 Angular 材料表單,客戶可以從中 select 一個值。
<form>
<mat-form-field>
<mat-label>CHOOSE ACCOUNT</mat-label>
<mat-select>
<mat-option *ngFor="let account of accounts" [value]="account.name">{{account.name}}</mat-option>
</mat-select>
</mat-form-field>
</form>
同時,我遵循這個指南: https://angular.io/start/forms ,它指導你實現formControlName
。 我想將此應用於<mat-option>
,以便我可以從下拉列表中獲取所選值。 我已經實現了指南中的所有步驟,但是formControlName
似乎不能很好地與<mat-option>
一起使用。
簡而言之:如何使用 Angular 材料(在上面完成)進行下拉,並能夠從下拉列表中獲取所選值?
formControlName與 mat-select 一起工作得很好。 您必須將“formControlName”屬性放在墊選擇中,而不是放在墊選項中。
<mat-select formControlName="myFormControl">
<mat-option *ngFor="let account of accounts" [value]="account.name">{{account.name}</mat-option>
</mat-select>
您可以使用 (onSelectionChange) 來實現這一點。
只需在 mat-option 標簽上使用它並處理自定義 function 中的表單值更改
組件.html
<mat-option
*ngFor="let account of accounts"
[value]="account.name"
(onSelectionChange)="selected($event)"
>{{account.name}}</mat-option>
組件.ts
selected(event) {
this.myForm.controls.nameOfValueToBeChanged.setValue([event.value]);
// or do whatever you want with event.value
}
不正確見下文以獲得更好的方法
您可以簡單地連接一個 [(NgModel)] ,它將選擇值鏈接到您選擇的 FormControl 的值,它本身只是在 your.ts 文件中創建的。 就像是:
比較
/.../
ngOnInit(){
this.form.registerControl('OptionsControl', this.formbuilder.control());
this.optionsControl = this.form.get('OptionsControl');
/../
比較html
<mat-select [(ngModel)]="optionsControl.value">
<mat-option *ngFor="let account of accounts" [value]="account.name">{{account.name}}</mat-option>
</mat-select>
___編輯___
表單控件的 value 屬性現在是只讀的,因此不能以這種方式直接分配。 相反,應選擇選擇作為監聽事件,如下所示:
<mat-select placeholder="Select your choice">
<mat-option (onSelectionChange)="optionsControl.setValue(account)" *ngFor="let account of accounts"
[value]="account.name">{{account.name}}
</mat-option>
</mat-select>
感謝@Adam 首先提到這個解決方案,我只是覺得有必要在這里糾正我的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.