Angular-ViewChild(Directive)返回指令中未定义的

时间:2018-11-01 13:53:56

标签: javascript angular

Angular V7.x

我正在创建将动态组件添加到指定容器的指令。我正在使用另一个指令将其标记为插入点,但是无论如何,ViewChild()都返回未定义。即使已在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 &mdash; it's free</h2>
      <ng-template appAlertHost></ng-template>
      ... (more content)
</form>

StackBlitz链接:VIEW ON STACKBLITZ

1 个答案:

答案 0 :(得分:1)

由于您的AlertHostDirective不在组件的HTML模板中使用,而是在表单的开始标记和结束标记之间使用,因此您需要使用ContentChild来访问该伪指令。