Reputation: 1686
Say I have a bunch components. Home, One, Two and Three. I use nav and routing to every page. I want to display a message "Hello" only on Home page. Then in other pages the message must be gone.
The main structure of app.component.html is
<h1>Angular Router</h1>
<nav>
<a routerLink="/crisis-center" routerLinkActive="active">Home</a>
<a routerLink="/heroes" routerLinkActive="active">Heroes</a>
<a [routerLink]="[{ outlets: { popup: ['compose'] } }]">Contact</a>
</nav>
<router-outlet></router-outlet>
<!--router-outlet name="popup"></router-outlet-->
<div style='font-size: 50px'>{{title}}</div>
You see every page displays "Hello". I don't want it.
Upvotes: 0
Views: 243
Reputation: 15083
You can watch for the router event changes and assign a variable when router matches home
title$ = this.router.events.pipe(
filter(event => event instanceof NavigationEnd),
map(({ url }: NavigationEnd) => /^\/crisis-center/.test(url)),
);
You can now use this variable in your template to show the contents you need
<div *ngIf="title$ | async" style='font-size: 50px'>{{title}}</div>
Upvotes: 1
Reputation: 677
The "Hello" text is coming on every page because you put it after router-outlet tag.
So all the components are being loaded in <router-outlet></router-outlet>
& then "Hello" text is shown after each component.
If you want this text should only on the Home component put this in the respective component template file.
app.component.html
<h1>Angular Router</h1>
<nav>
<a routerLink="/crisis-center" routerLinkActive="active">Home</a>
<a routerLink="/heroes" routerLinkActive="active">Heroes</a>
<a [routerLink]="[{ outlets: { popup: ['compose'] } }]">Contact</a>
</nav>
<router-outlet></router-outlet>
crisis-center-home.component.html
<p>Welcome to the Crisis Center</p>
<div style='font-size: 50px'>{{title}}</div>
crisis-center.component.ts
export class CrisisCenterComponent {
title = 'Hello';
}
Upvotes: 1
Reputation: 1662
Just move <div style='font-size: 50px'>{{title}}</div>
to the crisis-center.component.ts
's template:
@Component({
template: `
<h2>CRISIS CENTER</h2>
<router-outlet></router-outlet>
<div style='font-size: 50px'>{{title}}</div>
`
})
export class CrisisCenterComponent {
title = 'Hello';
}
Upvotes: 0