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

  • 本文关键字:指令 主机 组件 Angular angular
  • 更新时间 :
  • 英文 :


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

这是我的 html:

<div *placeholder="false" class="margin-2">here</div>

这是指令中的代码:

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);
}
}

使用此代码,当它是真的时,我看到了元素主机和作为组件的同级,但我希望组件在主机内。 我该怎么做?

请使用*ngIf。如本例所示

@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

最新更新