Я знаю, что есть и другие идеи, но я хочу использовать декораторы ng-template
, ng-content
и @ContenChild()
указанным ниже способом. Идея этого возникла, когда мы увидели реальное воплощение угловатых компонентов материала.
Здесь у меня есть два компонента:
- Компонент контейнера (приложение-контейнер)
- Дочерний компонент (приложение-потомок)
Я хочу, чтобы содержимое дочернего компонента приложения отображалось непосредственно в контейнере приложения.
У меня есть связанное решение: https://stackblitz.com/edit/ngtemplateoutlet-and-content-projection?file=src%2Fapp%2Fapp.component.html. Но это не совсем соответствует моим требованиям.
Желателен следующий html, в основном в app.component.html
:
<app-container>
<app-nav>
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
</app-nav>
<app-main>
<p>This is the content to be reflect.</p>
</app-main>
</app-container>
Что должно привести к следующему выводу:
<div class="container">
<nav role="navigation" class="navigation">
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
</nav>
<section role="main" class="main__content">
<p>This is the content to be reflect.</p>
</section>
</div>
Мои коды выглядят так
import { Component, ContentChild, AfterContentInit } from '@angular/core';
@Component({
selector: 'app-main'
template: `<ng-template><ng-content></ng-content></ng-template>`
})
export class AppMain {
}
@Component({
selector: 'app-nav'
template: `<ng-template><ng-content></ng-content></ng-template>`
})
export class AppNav {
}
@Component({
selector: 'app-container',
template: `
<div class="container">
<nav role="navigation" class="navigation">
<ng-container [ngTemplateOutlet="nav"></ng-container>
</nav>
<section role="main" class="main__content">
<ng-container [ngTemplateOutlet]="main"></ng-container>
</section>
</div>
`
})
export class AppContainer implements AfterContentInit {
@ContentChild(AppMain) main: AppMain;
@ContentChild(AppNav) nav: AppNav;
ngAfterContentInit() {
console.log(this.main);
console.log(this.nav);
}
}
ng-content
вместоng-container[ngTemplateOutlet]
внутриapp-container
? Я думаю, это более интуитивно понятно ... но, конечно, это может быть дело вкуса. - person julianobrasil   schedule 30.04.2020