angular 2,如果至少输入一个输入,则验证表单

angular 2, validate form if at least one input is typed

我是 Angular 的新手,我已经在网上搜索过,但没有找到适合我的情况的正确解决方案。

我有一个由 *ngFor 创建的动态表单。如果输入全部为空并显示警报 div,我需要禁用提交按钮;但如果这些表单中至少有一个包含与 '' 不同的内容,我需要启用提交。

这是我的 html 代码

<form class="form-inline" #form="ngForm">
    <div class="form-group" *ngFor="let meta of state.metaById; let i = index" style="margin: 5px">
      <label>{{meta.nome}}</label>
      <input type="text" class="form-control" #nome (blur)="inputInArray(nome.value, i);">
    </div>
    <button type="button" class="btn btn-primary" (click)="getCustomUnitaDocumentaliRow(this.param)" [disabled]="fieldNotCompiled">invia</button> 
</form>
<div class="alert-notification" [hidden]="!fieldNotCompiled">
    <div class="alert alert-danger">
      <strong>Va compilato almeno un campo.</strong>
    </div>
</div>

这是我的打字稿代码

inputInArray(nome: string, indice) {
if (this.state.controlloMetaId = true) {
  this.state.metadatoForm[indice] = nome;
}
// this.fieldNotCompiled = false;
for (const i in this.state.metaById) {
  console.log(this.state.metadatoForm);
  if (isUndefined(this.state.metadatoForm[i]) || this.state.metadatoForm[i] === '') {
    this.fieldNotCompiled = true && this.fieldNotCompiled;
  } else {
    this.fieldNotCompiled = false && this.fieldNotCompiled;
  }
  console.log(this.fieldNotCompiled);
}

使用此代码,我可以检查用户第一次在一个输入中键入内容,但如果它清空其中一个(或所有)则失败

感谢您的宝贵时间

更新

检查是否有任何输入得到不同于空或 space 的更改,只需执行以下操作:

<input ... #nome (input)="fieldNotCompiled = !nome.value.trim()" ....>

DEMO


您可以设置表单更改的侦听器:

@ViewChild('form') myForm: NgForm;
....
ngOnInit() {
    this.myForm.valueChanges.subscribe((value: any) => {
         console.log("One of the inputs has changed");
    });
}