Niels
Niels

Reputation: 426

Angular: Change option list in select dynamically

I have 2 selects filled with 2 object arrays in a modal:

<select class="browser-default" id="gebied" 
  [(ngModel)]="filteredGebied" 
  (ngModelChange)="onChange($event)">
    <option *ngFor="let gebied of list1" 
      value="{{gebied.id}}">{{gebied.beschrijving}}</option>
</select>

<select class="browser-default" id="domein" [(ngModel)]="filteredDomein">
  <option *ngFor="let domein of list2"
    value="{{domein.id}}">{{domein.beschrijving}}</option>
</select>

Now I want to change the items from the second select (list2) based on the selected item from list1.

onChange(list1Id){ 
...
this.list2 = ...
}

Problem is my select options in the second select (list2) don't change.

Sometimes I get the following error:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngForOf:

How can I fix this all?

Upvotes: 0

Views: 2826

Answers (2)

Niels
Niels

Reputation: 426

Apperently it works if I don't populate the second select on startup. But that's not a problem for my application.

Upvotes: 0

Taher
Taher

Reputation: 258

It should really work. Here I check for example if a is selected, that means according to your binding filteredGebied is 1 then list2 must change!

  export class AppComponent {
      list1 = [{ id: '1', beschrijving: 'a' }, { id: '2', beschrijving: 'b' }];
      list2 = [{ id: '1', beschrijving: 'aaa' }, { id: '2', beschrijving: 'bbbb' }];
      filteredGebied;
      filteredDomein;

      onChange(event) {
      if (this.filteredGebied === '1') {
        this.list2 = [{ id: '1', beschrijving: 'xxx' }, { id: '2', beschrijving: 'yyyy' }];
      }
     }
   }

Upvotes: 1

Related Questions