Reputation: 176
I have an observable this.result$ to which i am subscribing inside template . for e.g result is- [{id : "1", value: "test"}]. How can I add new object to this so that it become like this- [{id : "1", value: "test"},{id : "2", value: "new"}]
<mat-form-field *ngIf="result$ | async">
<mat-select [compareWith] = "compareFn">
<mat-option *ngFor = "let item of result$ | async" [value]="item">
{{item.value}}
</mat-option>
</mat-select>
</mat-form-field>
Upvotes: 0
Views: 607
Reputation: 197
I recommend you to change the code for this. In your .ts file for example:
objectList: any[] = [];
ngOnInit(): void {
this.result$.subscribe(r => {
this.objectList.push(r);
});
}
addNewObject(newObject: any): void {
this.objectList.push(newObject);
}
In your .html file use this.
<mat-form-field *ngIf="objectList && objectList.lenght > 0">
<mat-select [compareWith] = "compareFn">
<mat-option *ngFor = "let item of objectList" [value]="item">
{{item.value}}
</mat-option>
</mat-select>
</mat-form-field>
Upvotes: 1
Reputation: 1780
You can add new element in a observable array like this
this.result$ = this.result$.pipe(map((r) => [...r, { id: "2", value: "new" }]));
Upvotes: 2