I have template code like this:
<li *ngIf="isRoot() || isSoftware()">
Also i have this functions in my components code:
isRoot() {
return this.service.Level == 'Root';
}
isSoftwareOnly() {
return this.service.ServiceType == 'Software';
}
this.service gets by HTTP request.
How can I get request before template starts render? Now isRoot() and isSoftware() always return false, because this.service.Level and this.service.ServiceType are undefined
I see three ways:
First (quickest): Use constructor of your component (let's say that you have fetchData method in your service to make an http request:
export class Component {
constructor(private service: MyService) {
this.service.fetchData();
}
}
Second (slower): Use ngOnInit hook - data will be fetched in the same moment when initialization of view starts.
Third: Use ngOnChanges lifecycle hook (in my opinion this is not best practice in your usecase) - according to documentation:
Respond when Angular (re)sets data-bound input properties. The method receives a SimpleChanges object of current and previous property values. Called before ngOnInit() and whenever one or more data-bound input properties change.
More about lifecycle hooks in Angular.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With