加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

角度 – 基于条件的一个组件多个模板

发布时间:2020-12-17 09:15:14 所属栏目:安全 来源:网络整理
导读:所以这是交易.我有一个很好的写作和很多地方使用的组件.现在我需要使用相同的组件,但是要根据条件来渲染不同的模板. 我试了很多 1)尝试使用多个组件装饰器 – 没有运气 2)尝试了多层次的抽象,我刚才最终创建了更多的组件 – 坏主意 3)可以复制整个组件,只需
所以这是交易.我有一个很好的写作和很多地方使用的组件.现在我需要使用相同的组件,但是要根据条件来渲染不同的模板.

我试了很多

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内容只运行一次.所以当isWizard是true时,即使显示了div块,ng-content也不会运行(因为它在上面的块中运行).

5)而不是使用ngIf我也尝试过ngSwitch – 没有工作

我现在绝望了请帮忙 :)

据我所知,不能使用ng内容,但是您可以使用模板(或Angular 4中的ng模板)来实现此目的.所以,而不是将内容直接传递给您的组件,只需将其包装到< 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(); 
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读