【发布时间】:2020-05-29 13:10:48
【问题描述】:
我想始终使用默认 <ng-content> 和 可选 使用 命名 ng-content 呈现我相当简单的组件。如果那个命名的 ng-content 存在,它应该被附加的 html 包装。我确实找到了一个解决方案,但烦人的是我需要两个参考:
app.component.html(在哪里使用)
<app-header>
A minimal header
</app-header>
<hr>
<app-header>
A full header
<h2 #two two>a subhead</h2>
</app-header>
我的组件
import { Component, OnInit, ContentChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html'
})
export class HeaderComponent {
@ContentChild('two', {static: false}) twoRef: ElementRef;
}
header.component.html
<h4>default content</h4>
<ng-content>
</ng-content>
<h4>named contents</h4>
<div *ngIf="twoRef">
<b style="color: purple">
<ng-content select="[two]"></ng-content>
</b>
</div>
<ng-template [ngIf]="twoRef">TWO exists B</ng-template>
结果如预期,但我不喜欢我需要的两个属性:
<h2 #two two>
→ 有没有更好的方法,只使用一个引用/属性?
【问题讨论】:
标签: angular transclusion angular2-ngcontent