angular - 从角度 7 的控制器访问 ng-template 内部的 ngForm
问题描述
我有一个来自内部的 ng-template。我想通过我的控制器访问它,但我一直不确定。我已经测试了相同的代码,如果我不使用 ng-template,我可以使用 @ViewChild 访问它。但是,在我的情况下,我无法删除 ng-template,因为它是可重用模态组件的一部分。我不想在提交事件中访问它,我需要在ngAfterViewInit中访问。提前致谢。
<ng-template #template>
<form #formAccessor="ngForm" (ngSubmit)="submit(formAccessor)">
</form>
</ng-template>
在我的控制器里面
@ViewChild('formAccessor') ngForm:NgForm;
ngAfterViewInit(): void {
console.log(this.ngForm); //Prints undefined
}
解决方案
您需要将自引用传递给ng-template
using ngTemplateOutlet
,以便激活模板并呈现内部内容。
html
<ng-template #template [ngTemplateOutlet]="template">
<form #formAccessor="ngForm" (ngSubmit)="submit(formAccessor)">
</form>
</ng-template>
看这个演示
推荐阅读
- python - aws eb 部署错误:没有为 anaconda-client==1.6.9 找到匹配的发行版
- r - 对重复处理而不是参数执行 pca
- google-cloud-endpoints - 如何使用 Google Cloud Endpoints 设置自定义用户身份验证
- python - int() python3.6的无效文字
- iot - 为什么 Quectel BG96 在注册 CS 服务时卡住了?
- javascript - 我的 Getcookie 函数如何从 document.cookie 字符串中读取 cookie?
- node.js - Azure 函数 - 使用查询字符串重定向
- javascript - Javascript 能力:自治速度?
- vue.js - VueJS 动态路由和组件
- python-2.7 - 如何在 web.py 模板中获取当前 url 或输入参数