首页 > 解决方案 > 为输入动态创建角度 2+ 参考 ngModel 变量

问题描述

我想创建动态 ngModel 输入参考变量来检查所需的验证。

这是我的实现:

<div *ngFor="let priceId of prices">
  <input [(ngModel)]="getPriceValue(priceId)" #price="ngModel"/>
  <div *ngIf="price.invalid && (routePrice.dirty || price.touched)" class="invalid-feedback">
    required field!
 </div>
</div>

对于单一引用,它可以工作,但具有相同引用的多次引用#price它不起作用。因为它需要唯一的参考变量。

我想这样设置:

<input [(ngModel)]="getPriceValue(priceId)" #price_{{priceId}}="ngModel"/>

但它不起作用。

如何在角度 2+ 中设置动态参考变量?

谢谢

标签: angular

解决方案


在 HTML 文件中:

<form #f="ngForm">
  <input [(ngModel)]="getPriceValue(priceId)" #price="ngModel" name="price" required/> 
  <button class="btn" (click)="onClick(f)">btn</button>
</form>

在 TS 文件中:

onClick(f: NgForm) {
  this.checkForm(f);
}

checkForm(form) {
  const control = form.controls;
  Object.keys(control).forEach(controlName =>
    control[controlName].markAsTouched());
  Object.keys(control).forEach(controlName =>
    control[controlName].markAsDirty());
  const data = [];
  Object.keys(control).map((key) => {
    const newObj = {key, value: control[key]};
    data.unshift(newObj);
  });
  let title = '';
  for (let i = 0; i < data.length; i++) {
    const error = data[i].value.errors ? Object.keys(data[i].value.errors) : [];
    const inputKey = data[i].key;
    for (let x = 0; x < error.length; x++) {
      title = inputKey.toUpperCase() + '_' + error[x].toUpperCase();
      alert(title);
    }
  }
}

我使用此输入名称和验证属性进行动态验证。


推荐阅读