I tried all the examples given in stack over flow but its not executing and it showing so many errors could you please send me a code with explanation how to add a component only at initialization time. I want to execute my component at initial time only not in all the components.

1

There are 1 best solutions below

0
On

First you need a variable to keep track of the property. Something like homepageAlreadyViewed. Typically you would keep that in a service class, but you they have a bit of a learning curve (I do highly recommend learning all about Angular services and dependency injection though).

Another option would be to use session storage, which doesn't persist across hard reloads.

public class AppComponent implements OnInit {

  constructor(private router: Router) {}

  ngOnInit() {
    if (sessionStorage.homepageAlreadyViewed) {    
      this.router.navigate(['/somewhere-else']);
    }
    else {
      sessionStorage.homepageAlreadyViewed = true;
    }
  }
  
}