首页 > 解决方案 > Angular - ViewChild(Directive) 在指令中返回未定义

问题描述

角 V7.x

我正在创建一个向指定容器添加动态组件的指令。我正在使用另一个指令将其标记为插入点,但是 ViewChild() 无论如何都会返回 undefined。即使它是在ngAfterViewInit. 不过, Angular Docs 示例访问 ViewChild in 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 &mdash; it's free</h2>
      <ng-template appAlertHost></ng-template>
      ... (more content)
</form>

StackBlitz 链接:查看 STACKBLITZ

标签: javascriptangular

解决方案


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


推荐阅读