gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:03:59 24 4
gpt4 key购买 nike

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

最佳答案

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

关于javascript - Angular - ViewChild(Directive) 在指令中返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53102736/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com