首页 > 解决方案 > 从角度 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
}

标签: angular

解决方案


您需要将自引用传递给ng-templateusing ngTemplateOutlet,以便激活模板并呈现内部内容。

html

<ng-template #template [ngTemplateOutlet]="template">
   <form #formAccessor="ngForm" (ngSubmit)="submit(formAccessor)">
   </form>
</ng-template>

看这个演示


推荐阅读