Угловой V7.x
Я создаю директиву, которая добавляет динамический компонент в указанный контейнер. Я использую другую директиву для пометки в качестве точки вставки, но ViewChild () возвращает неопределенное значение, несмотря ни на что. Даже если к нему обращаются в ngAfterViewInit
. Пример Angular Docs обращается к ViewChild в ngOnInit
, хотя.
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);
}
}
бдительные-host.directive.ts
import { Directive } from '@angular/core';
@Directive({
selector: '[appAlertHost]'
})
export class AlertHostDirective {
constructor() { }
}
форма-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 Link: ПРОСМОТР НА STACKBLITZ