角度表格验证 - 如何包含来自ng-template的输入?

问题描述 投票:8回答:1

在模板驱动的表单中,我有两个输入。第二个来自ng-template。

<form #testForm="ngForm">
    First name <input type="text" name="firstName" [(ngModel)]="firstName" required> (required)
    <br>
    <ng-container *ngTemplateOutlet="inputTemplate"></ng-container>
</form>

inputTemplate看起来像这样:

<ng-template #inputTemplate>
    Last name <input type="text" name="lastName" [(ngModel)]="lastName" required> (required)
</ng-template>

两个输入都具有'required'属性,但是只要第二个输入为空,表单才有效。

有没有办法确保表单识别模板的输入?

但是:Kua zxsw指出

编辑:在我的实际应用程序中,ng-template来自另一个(第三方)组件,并使用模板引用加载,请参阅Plunker

我只找到了一些关于亲子组件问题的解决方案,但在这种情况下这些并不可行。

angular typescript angular-forms
1个回答
0
投票

我认为问题在于角度依赖注入。您的模板在其他地方定义,它使用Injector来定义它的位置。你的表单无法知道它并且你的输入不知道表单,即使它在DOM上面 - 它不在Injector树中。如果您可以访问模板,则可以将表单指令作为上下文传递,并在模板中使用它来链接输入和表单。

© www.soinside.com 2019 - 2024. All rights reserved.