【问题标题】:Angular6 transclusion / content projection: better conditional on wrapping htmlAngular6 嵌入/内容投影:更好地包装 html
【发布时间】: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


    【解决方案1】:

    你可以做一个辅助空指令并使用 ContentChild 查询它

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

    那么使用该组件只需要&lt;h2 two&gt;

    【讨论】:

    • 工作。谢谢!但令人遗憾的是,我需要将特定的指令导入到我打算使用我的模板的任何地方......(不像理想的那样自给自足)
    • 您可以在导出中使用HeaderComponentMyProjectionDirective 制作模块,并始终将它们成对导入到您需要的任何地方
    猜你喜欢
    • 1970-01-01
    • 2020-07-04
    • 2020-08-19
    • 2018-01-26
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 2018-08-06
    • 2017-10-27
    相关资源
    最近更新 更多