'Angular (latest): How to detect if Component is loaded via Router or Selector?
Assuming I have PageComponent
and it's accessible via a Selector and also in the Router as a Route, how can I tell if the Component is loaded via the selector <page-component>
or by the <router-outlet>
?
I found a hacky way of passing an attribute like this: @Input('viaSelector') viaSelector: boolean = false;
and then <page-component [viaSelector]="true"></page-component>
.
But is there something native that I can use to detect how a Component is loaded?!
Solution 1:[1]
Add a parameter when you are loading it via a route. if paramMap for route has that parameter available and is a valid parameter, you know it is loaded from route. If the parameter is null, you know is it loaded from selector.
this.activatedRoute.paramMap.subscribe(params => {
console.log(params.get('yourparameter'));
})
Solution 2:[2]
You probably want to look at Angular lifecycle hooks. By loaded what do you mean? Is the view loaded? Did the component got initialized?
The most common ones that I usually use are:
- ngOnInit, as cited from the angular official docs:
Initialize the directive or component after Angular first displays the data-bound properties and sets the directive or component's input properties.
- ngAfterViewInit:
Respond after Angular initializes the component's views and child views, or the view that contains the directive.
For more information about life cycle hooks checkout this link
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Amit Kumar Singh |
Solution 2 | AhmedSHA256 |