Home > Net >  Angular (latest): How to detect if Component is loaded via Router or Selector?
Angular (latest): How to detect if Component is loaded via Router or Selector?

Time:05-14

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?!

CodePudding user response:

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'));
})

CodePudding user response:

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

  • Related