我的组件有这个模板文件:
<form (ngSubmit)="onSubmit()" #scheduleForm="ngForm" *ngIf="schedule">
<div #placeholder></div>
</form>
我会在占位符div 中添加两个组件。这是我在ngOnInit中添加组件的代码:
const factory = this.componentFactoryResolver.resolveComponentFactory(ExternalComponent);
let ref = this.viewContainerRef.createComponent(factory);
ref.changeDetectorRef.detectChanges();
ref = this.viewContainerRef.createComponent(factory);
ref.changeDetectorRef.detectChanges();
其中外部组件是我会放入的组件。使用此代码,外部组件被添加到模板的末尾(登录表单之后)。我怎样才能把它放在 #placeholderdiv里?
这是设计使然。 https://github.com/angular/angular/issues/9035
如果您希望将动态组件放置在div
div
内部添加template
或ng-container
(它们未标记到 DOM 中)并使用它。
@Component({
selector: 'my-app',
template: `
<div>
<ng-container #placeholder></ng-container>
</div>`
})
export class AppComponent implements OnDestroy {
@ViewChild('placeholder', { read: ViewContainerRef }) placeholderContainer: ViewContainerRef;
compRef: ComponentRef<any>;
constructor(private resolver: ComponentFactoryResolver) {}
ngOnInit() {
const factory = this.resolver.resolveComponentFactory(MyComponent);
let compRef = this.placeholderContainer.createComponent(factory);
this.compRef = compRef;
}
ngOnDestroy() {
this.compRef.destroy();
}
}
普伦克示例