javascript - 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 — it's free</h2>
<ng-template appAlertHost></ng-template>
... (more content)
</form>
StackBlitz 链接:查看 STACKBLITZ
解决方案
由于您的 AlertHostDirective 未在组件的 HTML 模板中使用,而是在表单的开始标签和表单的结束标签之间使用,因此您需要使用ContentChild来访问您的指令。
推荐阅读
- javascript - 我正在尝试在表单提交中使用 ajax 但它不起作用
- gradient - 使用具有动量的随机梯度下降优化聚类中心和 DNN 参数
- python - 解析十六进制文件并逐字节解码
- c# - C# 在代码中使用 Azure DevOps 服务连接
- python - 当输入更大的数据时,熊猫滚动窗口返回陌生人和陌生人结果(错误)结果
- excel - VBA 保存 CSV(逗号分隔)
- c++ - 二维向量自定义谓词更大功能
- java - java中开始日期和结束日期的排序列表
- java - Apache Camel 问题在过滤器后出现 routingSlip
- css - CSS:有没有办法使悬停元素仅在单击后才处于活动状态?