I'm using asyncPipe
with a *ngIf
decorator that automatically subscribe/unsubscribe to an Observable that returns an object
within an <ng-container>...</ng-container>
.
So far so good, but inside the ng-container
tag, I want to pass the object
as an argument to a method doSomething(object)
.
The issue is that the method runs 5-8 times?
HTML template
<ng-container *ngIf="(user$ | async) as user">
{{ doSomething(user) }} <-- method executes multiple times
</ng-container
TypeScript file
class Component implements OnInit {
user: Observable<User>;
constructor() {}
ngOnInit() {
this.user$ = this.userService.getUser(id);
}
checkConfigs(object) {
console.log(object);
}
}
I've tested if the issue is the Observable that executes multiple times, but it runs once. And then thought the code within ng-container
is the issue, but that also runs once.
The question is different from this because I'm not asking if its advisable, but how to solve the issue. In practice, this should work. But because of Angulars changeDetection architecture, it doesn't work as expected with Observables, its even pointed out in this article things you didn't know about the AsyncPipe how to solve it by using changeDetection: ChangeDetectionStrategy.OnPush
.
you can change the components changeDetectionStrategy to onPush. after that, your doSomething function does not call several times. So basically it calls the function whenever the change is detected so that's why it is calling multiple times, so after changing detection technique that won't happen
Try this:
in your component: