2017-10-09 69 views
1

我对Angular很陌生,我已经在网上搜索,没有找到正确的解决方案。角2,如果至少输入一个输入,则验证表格

我有一个由* 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); 
} 

有了这个代码,我可以第一时间检查,在一个输入一个用户类型的东西,但它如果它清空其中一个(或全部),则失败

感谢您的时间

回答

1

UPDATE

检查是否有输入有一个变化是从空或空间,不同的只是在做:

<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"); 
    }); 
} 
+0

你能更好地解释我吗?它不适用于我,但我当然需要更改HTML实际上有“myForm”... – Fjordo

+0

我试过了,但它不起作用。我也删除了(模糊),认为它可能有些问题...但没有日志出现 – Fjordo

+0

请检查更新后的文章 – Vega