Reputation: 3500
I'm using a few REST services to gather data and then change the value of an Observable in my component code. I'm trying to use an *ngIf to show/hide div tags based on the result. However, it isn't working, the *ngIf is not updating based on the change to the Observable.
Do I have to trigger change detection? What's the best way to achieve this in Angular 7? Here's one example I tried:
HTML:
<div *ngIf="isAnimal$">
<p>animal</p>
</div>
Component:
public isAnimal$: Observable<boolean> = of(false);
...
ngOnInit() {
checkAnimal();
}
private checkAnimal() {
this._dataService.getData()
.subscribe((result) => {
if (result === 'animal') {
this.isAnimal$ = of(true);
}
});
}
I also tried creating a simple service and that didn't work either. Like this: Angular *ngIf binding to function
Upvotes: 2
Views: 6248
Reputation: 8004
I suggest the following:
HTML:
<div *ngIf="isAnimal">
<p>animal</p>
</div>
Component:
public isAnimal: boolean = false;
ngOnInit() {
checkAnimal();
}
private checkAnimal() {
this._dataService.getData().subscribe(
(result) => {
if (result === 'animal') {
this.isAnimal = true;
}
},
(error) => {
console.log(error);
}
);
}
I am not sure, but I think you could use the async pipe instead using your implementation:
<div *ngIf="isAnimal$ | async">
<p>animal</p>
</div>
The reason your solution is not working is because isAnimal$
is an observable that has to be resolved. The async pipe could do this, but I prefer the first solution to be honest. It does not seem natural to me to create another observable of(true)
in your subscription.
Upvotes: 5