kerpekri
kerpekri

Reputation: 377

How to bind reactive form builder properties to select

So I am struggling to get this working, what I want to do is to bind reactive form builder properties to the select option values using a list. This is my user model:

export interface User {
  id: number;
  firstName: string;
  lastName: string;
  about: string;
  features: IFeatureList[];
}

export interface IFeatureList {
  FeatureId: string;
  FeatureName: string;
}

Ts file binding:

this.form = this.formBuilder.group({
  firstName: ['', Validators.required],
  lastName: ['', Validators.required],
  about: [],
  features: this.formBuilder.array([ this.createItem() ])
});

  createItem(): FormGroup {
  return this.formBuilder.group({
    FeatureId: '',
    FeatureName: ''
  });
}

Do I even need to use formBuilder.array to add the group?

Template:

<select class="form-control" formArrayName="features">
<option *ngFor="let item of form.get('features').controls; let i = index;" 
[value]="item.FeatureId">
  <div [formGroupName]="i">
    {{item.FeatureName}}
  </div>
  </option>

I am also not sure about the form.get('features').controls here, do I need to use just a simple ngFor?

Example - https://stackblitz.com/edit/angular-ndj21m?file=src%2Fapp%2Fapp.module.ts

What I have tried in the .ts file:

this.form = this.formBuilder.group({
  firstName: ['', Validators.required],
  lastName: ['', Validators.required],
  about: [],
  features: []
});

Template file:

<select class="form-control" formControlName="features">
<option *ngFor="let item of user" 
[value]="item.FeatureId">
    {{item.FeatureName}}
  </option>

Upvotes: 0

Views: 661

Answers (1)

Manoj
Manoj

Reputation: 507

You're accessing the root object and not the array.

<select class="form-control" formControlName="features">
    <option *ngFor="let item of (user|async).features" 
    [value]="item.FeatureId">
        {{item.FeatureName}}
      </option>
  </select>

I modified the ngFor and it's working

Upvotes: 1

Related Questions