Angular6转换/内容投影:更好地包装html

Angular6转换/内容投影:更好地包装html,angular,transclusion,angular2-ngcontent,Angular,Transclusion,Angular2 Ngcontent,我希望始终使用默认的和命名的ng内容来呈现相当简单的组件。如果命名的ng内容存在,则应使用其他html对其进行包装。我确实找到了一个解决方案,但令人烦恼的是,我需要两个参考: app.component.html(使用它的地方) 最小标题 完整的标题 分目 我的组件 import { Component, OnInit, ContentChild, ElementRef } from '@angular/core'; @Component({ selector: 'app-hea

我希望始终使用默认的
和命名的
ng内容来呈现相当简单的组件。如果命名的ng内容存在,则应使用其他html对其进行包装。我确实找到了一个解决方案,但令人烦恼的是,我需要两个参考:

app.component.html(使用它的地方)


最小标题

完整的标题 分目
我的组件

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>
默认内容
命名内容
存在两个B
结果如预期,但我不喜欢我需要的两个属性:

<h2 #two two>


→ 有没有更好的方法,只处理一个reference/attrib?您可以执行helperempty指令并使用ContentChild查询它

@Directive({selector: '[two]'}) export class MyProjectionDirective {}
....
@ContentChild(MyProjectionDirective) ref: MyProjectionDirective;

只有
才能使用该组件工作。非常感谢。但遗憾的是,我需要将特定指令导入到我打算使用模板的任何地方。。。(不像期望的那样自给自足)您可以在导出中使用
HeaderComponent
MyProjectionDirective
创建模块,并始终将它们成对导入到需要的任何位置