简体   繁体   English

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

[英]Angular - ViewChild(Directive) returns undefined in Directive

Angular V7.x角 V7.x

I am creating a Directive that adds a dynamic component to the specified container.我正在创建一个将动态组件添加到指定容器的指令。 I am using another Directive to mark as an insertion point but, ViewChild() returns undefined no matter what.我正在使用另一个指令来标记为插入点,但是无论如何, ViewChild() 都返回 undefined 。 Even if it's accessed in ngAfterViewInit .即使它是在ngAfterViewInit访问的。 Angular Docs example accesses ViewChild in ngOnInit , though.不过,Angular Docs 示例在ngOnInit访问 ViewChild 。

alert.directive.ts 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警报host.directive.ts

import { Directive } from '@angular/core';

@Directive({
  selector: '[appAlertHost]'
})
export class AlertHostDirective {

  constructor() { }

}

form-signup.html表单注册.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 Link: VIEW ON STACKBLITZ StackBlitz 链接:在 STACKBLITZ 上查看

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM