maria
maria

Reputation: 159

angular 4 change templateurl after if

Okay so i have a component file with a templateurl

Within that template IT is router outlet Thats Okay. Is there a way to change the component path file if Some conditions are met within the component ?

the main idea is to check if user is online , if it is show index1, else show index2.

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
   if(USERISONLINE) {
     changetemplateurl to something else
   }
}

Upvotes: 0

Views: 482

Answers (2)

Tanmay
Tanmay

Reputation: 335

If I understood your scenario correctly, based on login flag you need to perform two separate operation

You can use routelink if you are using hyperlinks

<li><a [routerLink]="['/Login',{Flag:'Success'}]">Dashboard</a></li>

or Component Attribute

<Login [Flag]="Success"></Login>

You will get this Flag in your component, based on that you can perform business logic inside.

Upvotes: 1

Saiyaff Farouk
Saiyaff Farouk

Reputation: 5633

Assuming that you're trying to redirect to a component if the user is already logged in. If not another component.

You can try this.

ngOnInit() {
    if(USERISONLINE) {
     this.router.navigate([app/path1]); // whatever the path configured in router if the user is online
   } else {
     this.router.navigate([app/path2]); // whatever the path configured in router if the user is not online
   }
}

Don't forget to import the router and reference it - Dependency Injection and implements part of the lifecycle hook

But, Recommended way of doing this is using router guards since this redirection happens in the OnInit life cycle of the component. But, for your approach, this answer will work

Upvotes: 1

Related Questions