[英]How to assign values in an Angular form without an input element or hiding the UI element?
我正在處理這個模板驅動的表單,其中有一個下拉列表。
下拉列表有一個ID作為值和Name作為顯示值。
當我提交表單時,我需要值ID和Name都在表單輸出中
<mat-form-field>
<mat-label>State</mat-label>
<mat-select [(ngModel)]="data.stateCode" name="StateCode" #yddfyty>
<mat-option *ngFor="let state of stateOptions" [value]="state.ID">
{{state.name}}
</mat-option>
</mat-select>
</mat-form-field>
提交表單后,我得到一個 JSON
{
StateCode: "Option I select in the Dropdown"
}
當我提交表單時,我還希望 StateName 出現在表單輸出中。
如何將下拉列表中選擇的 StateName 分配給模板驅動表單中的模型屬性?
我可以想到一種方法,我們可以使用一個元素並隱藏該元素,還有其他方法嗎?
是提交后在 Typescript 文件中執行此操作的唯一方法嗎?
ViewChild
在這些情況下派上用場:
HTML文件:
<mat-form-field>
<mat-label>State</mat-label>
<mat-select name="StateCode" #ElementRef>
<mat-option *ngFor="let state of stateOptions" [value]="state.ID">
{{state.name}}
</mat-option>
</mat-select>
</mat-form-field>
組件 TS 文件:
首先聲明一個viewchild變量:
@ViewChild('ElementRef') stateElement: any;
稍后您可以在提交表單時使用此變量:
OnSubmit(){
let selectedStateCode = this.stateElement.nativeElement.value//selected dropdown value
let selectedStateText = this.stateElement.nativeElement.textContent //selected dropdown text
//rest of your submit code;
}
是的,根據給定的限制,您必須處理.ts
文件中的表單提交。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.