我需要在结构指令的容器中放置一个动态组件。当指令的值为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);
}
}在这段代码中,当它为true时,我看到了元素host和组件的同级,但我希望组件在host内部。我怎么能做到这一点?
发布于 2020-01-21 18:24:18
请使用*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
https://stackoverflow.com/questions/59838790
复制相似问题