【问题标题】:Angular - ViewChild(Directive) returns undefined in DirectiveAngular - ViewChild(Directive) 在指令中返回未定义
【发布时间】: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 &mdash; it's free</h2>
      <ng-template appAlertHost></ng-template>
      ... (more content)
</form>

StackBlitz 链接:VIEW ON STACKBLITZ

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

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

    【讨论】:

    • 还是undefined
    • 问题似乎是您使用 AlertDirective 作为structural directive。如果你在没有星号的情况下使用它,它可以工作。有没有必要?查看更新 blitzstack:stackblitz.com/edit/…
    猜你喜欢
    • 2023-01-25
    • 2019-10-19
    • 2017-01-08
    • 2019-07-28
    • 2020-03-25
    • 2016-04-29
    • 2017-03-11
    • 2023-03-21
    相关资源
    最近更新 更多