简体   繁体   English

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

[英]Bind values to array in an object from controls Angular 6

I'm using the below entity class,我正在使用以下实体 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, 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>

Component.ts组件.ts

 submitForm(formValue: Details) {
    console.log(formValue);
}

I can get the value individually from all the controls, but is there any way to bind the Language values(3 controls) automatically to the list object in the class so that i can pass the object for save.我可以从所有控件中单独获取值,但是有什么方法可以将语言值(3 个控件)自动绑定到 class 中的列表 object 以便我可以通过 object 进行保存。 Also to re-bind the data into the controls during an edit.还可以在编辑期间将数据重新绑定到控件中。

Any easier way to?有更简单的方法吗?

As you are using the ReactiveForms approach for data binding you need to use the FormGroup so you will get the updated data automatically in both the places in your Html as well an in your Components.ts file.当您使用ReactiveForms方法进行数据绑定时,您需要使用FormGroup ,以便在 Html 以及 Components.ts 文件中的两个位置自动获取更新的数据。

To get the data in component.ts file you can use it like要获取 component.ts 文件中的数据,您可以像这样使用它

this.userForm.getRawValue()

If you want to get the data in your html then you need to use it like:如果您想获取 html 中的数据,那么您需要像这样使用它:

 <span>{{userForm.getRawValue() | json}}</span>

STACKBLITZ堆栈闪电战

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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