首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Angular 2中将组件放入指令的主容器中?

如何在Angular 2中将组件放入指令的主容器中?
EN

Stack Overflow用户
提问于 2020-01-21 18:13:50
回答 1查看 99关注 0票数 0

我需要在结构指令的容器中放置一个动态组件。当指令的值为true时,我需要将内容隐藏在容器中并放置一个组件,当为false时,我需要显示容器及其内容。

这是我的html:

代码语言:javascript
复制
 <div *placeholder="false" class="margin-2">here</div>

以下是指令中的代码:

代码语言:javascript
复制
ngOnInit(): any {
    // If the element its hided
    if (this.placeholder) {
        const temp = this.viewContainerRef.createEmbeddedView(this.templateRef);
        const containerFactory = this.componentFactoryResolver.resolveComponentFactory(EntryComponent);
        this.viewContainerRef.createComponent(containerFactory);
    } else {  // If its showed
        this.viewContainerRef.createEmbeddedView(this.templateRef);
    }
}

在这段代码中,当它为true时,我看到了元素host和组件的同级,但我希望组件在host内部。我怎么能做到这一点?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-21 18:24:18

请使用*ngIf。如本例所示

代码语言:javascript
复制
@Component({
selector: 'ng-if-simple',
template: `
    <button (click)="show = !show">{{show ? 'hide' : 'show'}}</button>
    show = {{show}}
    <br>
    <div *ngIf="show">Text to show</div>
`
})
export class NgIfSimple {
  show: boolean = true;
}

更多信息请点击此处https://angular.io/api/common/NgIf

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59838790

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档