Angular 2 Multiple layout routing

2019-09-19 16:20发布

On my angular 2 app, I have a completely different layout between my home page and the rest of the app. The rest of the app have only a nav in common.

My url looks like :

http://localhost:4200/ <== this is my home page

http://localhost:4200/cgu <== a page with nav in common

http://localhost:4200/abc <== a page with nav in common

Can someone explain to me the best way to do this ?

I tried to reproduce this solution :

How to switch layouts in Angular2

But it doesn't work, or I made mistake to adapt it to my case.

EDIT:

Finally I tried your solution So I created the navigation.service.ts

@Injectable()
export class NavigationService {
  isHomePage: boolean;
}

In my home.component.ts

@Component({
  styleUrls: ['home.css'],
  templateUrl: './home.component.html',
})
export class HomeComponent {

  constructor(private navigationService: NavigationService) {
    navigationService.isHomePage = true;
  }
}

In my app.component.ts I try to get the isHomePage value:

export class AppComponent {

  constructor(private navigationService : NavigationService) {

    console.log("HELLO");
    console.log(navigationService.isHomePage);
    if(navigationService.isHomePage)
      console.log("HOME");
}}

navigationService.isHomePage is undefined

What's my mistake ?

1条回答
别忘想泡老子
2楼-- · 2019-09-19 16:56

I would recommend reading the official documentation as it is very concise and uses examples.

The Angular Router enables navigation from one view to the next as users perform application tasks.

You would bind a component to a route so that when a user navigates to it it shows the right template.

In order to have a shared navigation, you must place it outside of your router-outlet, therefore the content of your views will be contained in said outlet but not the navigation.

__

If you do not want to display it in your homepage you may do the following:

Create a NavigationService that contains a boolean isHomepage, set it to false once you leave the home page, and true once you navigate to it. Inject it in your navigation component, and in your template:

<nav *ngIf="!_navigationService.isHomePage"></nav>

This way it will only be displayed out of the home page.

查看更多
登录 后发表回答