Angular [Material] - Inject components dynamically into a template

Asked

Viewed 709 times

0

I have two static elements in the project, which will never go away, only the content, these are the top menu and a sidenav, from the route I want to insert components inside the <mat-sidenav-content></mat-sidenav-content> as I navigate, the principle is simple, but it is another component, so it would be to insert components inside the template.

   <!-- sidenav.component.html -->

<mat-sidenav-container>
  <mat-sidenav mode="side" opened>
    <a>teste</a>
  </mat-sidenav>
  <mat-sidenav-content>
    <!-- componentes aqui -->
  </mat-sidenav-content>
</mat-sidenav-container>


<!-- top-menu.component.html -->

<mat-toolbar color="primary">
  <p>works</p>
</mat-toolbar>

<!-- index.component.html -->
<app-top-menu></app-top-menu>
<app-sidenav></app-sidenav>

<p>index component</p>

In app.component.html I only have <router-outlet></router-outlet>, then the idea is that every time a user accesses the app, drop in the login and then load this sidenav and any other mat-sidenav-content

Theoretically I would do this in a Component, add the templates and the content would go in the correct location, however, it is below the sidenav:

Follows images: inserir a descrição da imagem aqui

Component index inserted below template: inserir a descrição da imagem aqui

As it should be:

inserir a descrição da imagem aqui

1 answer

0


So that the <mat-sidenav> work properly it is necessary to design all the content of the app within tag <mat-sidenav-content>. To place one component inside the other use the tag <ng-content>. It works like a slot so that you can insert tags/content within your angular component.

<!-- sidenav.component.html -->
<mat-sidenav-container>
  <mat-sidenav mode="side" opened>
    <a>teste</a>
  </mat-sidenav>
  <mat-sidenav-content>
    <!-- componentes aqui -->
    <ng-content></ng-content>
  </mat-sidenav-content>
</mat-sidenav-container>

With this, it is now possible to place the component <app-top-menu> within of the component <app-sidenav>:

<!-- index.component.html -->
<app-top-menu>
  <app-sidenav></app-sidenav>
</app-top-menu>

References:

  • 1

    With a few tweaks, this is really what I wanted, what I’ve changed is that <app-top-menu> gets isolated above and ng-content goes inside the sidenav content, with this, the content I put inside the sidenav tag and works perfectly, thank you, you helped me finish =D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.