繁体   English   中英

从控件 Angular 6 将值绑定到 object 中的数组

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM