簡體   English   中英

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

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

角 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);
  }
}

警報host.directive.ts

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

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

  constructor() { }

}

表單注冊.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 上查看

由於您的 AlertHostDirective 不是在組件的 HTML 模板中使用,而是在表單的開始和表單的結束標記之間使用,因此您需要使用ContentChild來訪問您的指令。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM