【发布时间】:2018-11-01 13:53:55
【问题描述】:
Angular V7.x
我正在创建一个向指定容器添加动态组件的指令。我正在使用另一个指令将其标记为插入点,但是 ViewChild() 无论如何都会返回 undefined。即使它是在ngAfterViewInit 中访问的。不过,Angular Docs 示例访问 ngOnInit 中的 ViewChild。
alert.directive.ts
import { Directive, ViewChild, TemplateRef, ViewContainerRef, Input } from '@angular/core';
import { AlertHostDirective } from './alert-host.directive';
@Directive({
selector: '[appAlert]'
})
export class AlertDirective {
@ViewChild(AlertHostDirective) alertHost;
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef
) {}
ngAfterViewInit() {
console.log(this.alertHost); // undefined
}
ngOnInit() {
console.log(this.alertHost); // undefined
}
@Input() set appAlert(name: string) {
this.viewContainer.createEmbeddedView(this.templateRef);
}
}
alert-host.directive.ts
import { Directive } from '@angular/core';
@Directive({
selector: '[appAlertHost]'
})
export class AlertHostDirective {
constructor() { }
}
form-signup.html
<form *appAlert="'signupForm'" class="form-signup" (submit)="onSubmit($event)" [formGroup]="signupForm">
<h2 class="mb-4">Sign Up — it's free</h2>
<ng-template appAlertHost></ng-template>
... (more content)
</form>
StackBlitz 链接:VIEW ON STACKBLITZ
【问题讨论】:
标签: javascript angular