angularrouter-outlet

How to have a different layout at AppComponent level?


I have created an app that has a menu in the AppComponent which means all child pages/components will have it according to the next pseudo code:

<menu></menu> <--I need this removed in the new page-->
<router-outlet></router-outlet>

Now I need a new page without the menu. How can I achieve it?

I hope to have explained my problem well. Thanks in advance.


Solution

  • This is more common that you'd think, scenarios such as having an app.component.html side menu that you'd want to hide on login.component or register.component have the behaviour you're looking to achieve.

    They way I particularly do it, is having an @injectable({}) service I call menu.service, which is passed down to components as needed.

    Try the following:

    app.component.html

    <div class="appComponent">
       <div class="sideMenu" *ngIf="menuService.show">
              ...
       </div>
    </div>
    

    menu.service

    @Injectable({
        providedIn: 'root'
    })
    export class MenuService {
        public shown = false;
        constructor(){}
    
        setShown(bool:boolean){
            this.shown = bool;
        }    
    }
    

    This menu service can be injected on your component's constructor that you want to hide, and can be toggled in / out with onInit & onDestroy handlers

    no-menu.component.ts

    @Component({
      ...
    })
    export class NoMenuComponent implements OnInit, OnDestroy {
        constructor(public menuService: MenuService){}
    
        ngOnInit() {
            this.menuService.setShown(false);
        }
        ngOnDestroy(){
            // Recovers menu on exiting component
            this.menuService.setShown(true);
        }
    
    }
    

    Hope this helps you out, you can adapt it to your needs :)