Angular wont update UI on array ngModel change

Viewed 708

I have a <select> that is two-way bound to myArray in MyComponent. I want to manipulate the content of myArray based on an asyc call to a service. When I push the new data into myArray the update will not be reflected in the select. If I instantiate the array with the data it will.

Why is that and how can I push instead of instantiate the array?

export class Foo {
    constructor(name: string) {}
}

export class MyComponent implements OnInit {

    myArray = [];        

    ngOnInit() {
        this.service.get().then((data) => {
           //This won't work: 
           this.myArray.push(this.doSomething(data));

           //This will work:
           this.myArray = [ this.doSomething(data) ];
        }
    } 

    doSomething(data: any): Foo {
        return new Foo("hello");
    }
}

<select multiple name="myArray" ngModel [(ngModel)]="myArray" >
    <option *ngFor="let a of ..." [ngValue]="...">...</option>  
</select>
2 Answers
Related