Best method to set different layout for different pages in angular 4

后端 未结 4 688
孤街浪徒
孤街浪徒 2020-12-04 06:16

I am new to angular 4. What I\'m trying to achieve is to set different layout headers and footers for different pages in my app. I have three different cases:

4条回答
  •  猫巷女王i
    2020-12-04 06:54

    You can solve the problem using ng-content + ViewChild injection of layout into each page component that uses that specific layout.

    Using the router for this common use case always seemed like a workaround to me. What you want is similar to Layouts in Asp.Net MVC or MasterPages in WebForm etc.

    After struggling with this I ended up with something like this:

    see working demo: https://stackblitz.com/edit/angular-yrul9f

    shared.component-layout.ts

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'shared-component-layout',
      template: `
      
    Layout title: {{layoutHeader}}
    ` }) export class SharedComponentLayout { layoutHeader: string; hideLayoutHeader: boolean; }

    page.component-base.ts

    import { Component, ViewChild } from '@angular/core';
    import { SharedComponentLayout } from './shared.component-layout';
    
    export abstract class PageComponentBase {
        @ViewChild('layout') protected layout: SharedComponentLayout;
    }
    

    login.component.ts - without header

    import { Component } from '@angular/core';
    import { PageComponentBase } from './page.component-base';
    
    @Component({
      selector: 'login-component',
      template: `
      
        
    LOGIN BODY
    ` }) export class LoginComponent extends PageComponentBase { ngOnInit() { this.layout.hideLayoutHeader = true; } }

    home.component.ts - with header

    import { Component } from '@angular/core';
    import { PageComponentBase } from './page.component-base';
    
    @Component({
      selector: 'home-component',
      template: `
      
        
    HOME BODY
    ` }) export class HomeComponent extends PageComponentBase { ngOnInit() { this.layout.layoutHeader = 'Home component header'; } }

提交回复
热议问题