![](/img/trans.png)
[英]Angular 2 - How to automatically bind object values to related to Form Controls?
[英]Bind values to array in an object from controls Angular 6
我正在使用以下實體 class,
public class Details
{
public Test()
{
this.Languages = new List<Language>();
}
public string Id { get; set; }
public string Name { get; set; }
public List<Language> Languages { get; set; }
}
HTML,
<mat-form-field class="example-full-width">
<input matInput placeholder="Name" formControlName="Name">
<mat-hint align="end">Not more then 50 characters long.</mat-hint>
</mat-form-field>
<mat-form-field class="example-full-width">
<mat-label>Mother Language</mat-label>
<mat-select formControlName="motherTongueId" required>
<mat-option *ngFor="let selected of languageList" [value]="selected.id">
{{selected.name}}
</mat-option>
</mat-select>
<mat-error *ngIf="hasError('motherTongueId', 'required')">Mother Language is required</mat-error>
</mat-form-field>
<mat-form-field class="example-full-width">
<mat-label>Other Language 1</mat-label>
<mat-select formControlName="languageKnown1Id" >
<mat-option *ngFor="let selected of languageList" [value]="selected.id">
{{selected.name}}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="example-full-width">
<mat-label>Other Language 2</mat-label>
<mat-select formControlName="languageKnown2Id" >
<mat-option *ngFor="let selected of languageList" [value]="selected.id">
{{selected.name}}
</mat-option>
</mat-select>
</mat-form-field>
組件.ts
submitForm(formValue: Details) {
console.log(formValue);
}
我可以從所有控件中單獨獲取值,但是有什么方法可以將語言值(3 個控件)自動綁定到 class 中的列表 object 以便我可以通過 object 進行保存。 還可以在編輯期間將數據重新綁定到控件中。
有更簡單的方法嗎?
當您使用ReactiveForms
方法進行數據綁定時,您需要使用FormGroup
,以便在 Html 以及 Components.ts 文件中的兩個位置自動獲取更新的數據。
要獲取 component.ts 文件中的數據,您可以像這樣使用它
this.userForm.getRawValue()
如果您想獲取 html 中的數據,那么您需要像這樣使用它:
<span>{{userForm.getRawValue() | json}}</span>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.