所以这就是交易。我有一个写得很好并且在很多地方使用的组件。现在我需要使用相同的组件,但希望根据条件呈现不同的模板。
我尝试了很多。
1)尝试使用多个组件装饰器 - 没有运气
2)尝试了多个抽象级别,我最终创建了更多组件 - 坏主意
3)可以从字面上复制整个组件,然后只更改选择器和模板 - 坏主意
4)目前我正在尝试这个:
<div *ngIf="!isWizard">
<ul class="nav" role="tablist">
<ng-content select="tab-link"></ng-content>
</ul>
<ng-content select="tab-content"></ng-content>
</div>
<div *ngIf="isWizard">
<nav class="nav-panel sidenav">
<ng-content select=".wizard-title"></ng-content>
<ul class="nav" role="tablist">
<ng-content select="tab-link"></ng-content>
</ul>
</nav>
<main class="settings-panel content-area">
<ng-content select="tab-content"></ng-content>
</main>
</div>
我将 isWizard 属性设置为 true/false。
现在的问题是,ng-content 只运行一次。因此,当 isWizard 为 true 时,即使显示了 div 块,ng-content 也不会运行(因为它在上面的块中运行)。
5)我没有使用 ngIf,而是尝试了 ngSwitch - 没有用
我现在很绝望。请帮忙 :)
据我所知,这不能使用ng-content
但你可以使用来实现这一点templates
(or ng-templates
在 Angular 4+ 中)。因此,不要将内容直接传递给组件,只需将其包装在<template>
像那样:
<my-component [isWizard]="true">
<template>Hello World!</template>
</my-component>
然后你需要将模板注入到你的组件中@ContentChild(TemplateRef)
并根据需要多次渲染它。
@Component({
selector: "my-component",
template: `
<div *ngIf="!isWizard">
first: <template [ngTemplateRenderer]="template"></template>
</div>
<div *ngIf="isWizard">
second: <template [ngTemplateRenderer]="template"></template>
</div>`
})
export class MyComponent {
@ContentChild(TemplateRef)
private template: TemplateRef<any>;
@Input("isWizard")
private isWizard: boolean;
}
最后一件事,我们的组件使用ngTemplateRenderer
这是一个简单的实用指令,用于呈现通过引用传递的模板。这是该指令的代码:
@Directive({ selector: '[ngTemplateRenderer]'})
export class TemplateRenderer implements OnInit, OnDestroy {
@Input("ngTemplateRenderer")
private template: TemplateRef<any>;
private view: EmbeddedViewRef<any>;
constructor(private container: ViewContainerRef) {}
ngOnInit(): void {
this.view = this.container.createEmbeddedView(this.template);
}
ngOnDestroy(): void {
this.view.destroy();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)