简体   繁体   中英

Bind values to array in an object from controls Angular 6

I'm using the below entity 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>

Component.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. 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.

To get the data in component.ts file you can use it like

this.userForm.getRawValue()

If you want to get the data in your html then you need to use it like:

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

STACKBLITZ

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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