【问题标题】:Input Validation Template Reference ngFor输入验证模板参考 ngFor
【发布时间】:2020-05-20 16:24:12
【问题描述】:

我正在尝试验证 *ngFor 循环中所需的输入。 但我无法获得唯一的模板参考。 在提交时,所有输入字段都是必需的/如果至少填写了一个,则不需要。

我尝试像 #optionContent_{{i}} 一样声明模板引用,但我可以将其填写在 [ngClass] 中。

有什么帮助吗?

<form name="form" (ngSubmit)="f.form.valid && addOption()" #f="ngForm" novalidate>
 <div class="row" *ngFor="let size of optionModel.optionContent let i = index">
   <div class="col-12">
     <label for="optionContent_{{i}}>Name Option</label>
        <input id="optionContent_{{i}}"
               type="text"
               #optionContent="ngModel"
               [ngClass]="{ 'is-invalid': f.submitted && optionContent.invalid }"
               required
               name="optionContent"
               [(ngModel)]="size.name"  class="form-control">
   </div>
  </div>
</form>

【问题讨论】:

    标签: html angular


    【解决方案1】:

    问题在于 name 属性它们都具有相同的名称,所以 ngForm 会混淆尝试添加动态名称

    <input ... name="optionContent{{i}}" ../>
    

    【讨论】:

    • 我已经试过了。但是我应该如何将它添加到 ngClass: [ngClass]="{ 'is-invalid': f.submitted && optionContent{{i}}.invalid }" 不起作用。
    • 您通过模板引用在 ngclass 中引用,并保留模板引用,因为它只是更改名称属性。模板引用是循环范围的
    • 就是这样...谢谢!
    猜你喜欢
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    相关资源
    最近更新 更多