验证Angular 2 +

时间:2018-08-09 02:43:56

标签: angular typescript angular-forms angular-template-form

In this plunk我有一个Angular表单,其中包含一个输入字段,后跟一组输入字段。我需要验证这些字段中的任何一个都不为空。

单个字段工作良好,但是我正在努力验证字段数组,显示表单时出现错误Error: Cannot assign to a reference or variable!。有什么想法可以解决这种尝试吗?

@Component({
  selector: 'my-app',
  template: `
   <form #f="ngForm" name="form" (ngSubmit)="ok(f.form)" novalidate>
       <input name="singleField" id="singleField" [(ngModel)]="field1"  
              #singleField="ngModel" required />
       <div *ngIf="singleField.touched || submitted" class="errorMsg">
            <label *ngIf="singleField.control.hasError('required')">
                Field is required
            </label>
       </div>
       <br/><br/>
       <div *ngFor="let field2 of manyFields; let i = index">
           <input name="field" id="field" [(ngModel)]="field2"  
                  #field="ngModel" required />
           <div *ngIf="field.touched || submitted" class="errorMsg">
                <label *ngIf="field.control.hasError('required')">
                    Field is required
                </label>
           </div>
       </div>
       <br/><br/>
       <button type="submit">Submit</button>
   </form>
  `,
  styles: [`
    .errorMsg {
      color: red;
    }
  `]
})
export class App {

       field1: string = 'delete this';
       manyFields: string[] = ['Field 1', 'Field 2', 'Field 3'];

       ok(form: any){
            if (form.valid)
                 alert("Form is valid");
            else     
                 alert("Form is NOT valid");
       }
}

1 个答案:

答案 0 :(得分:1)

Error: Cannot assign to a reference or variable错误,因为[(ngModel)]="field2"您无法断定field2

这解决了错误并使required验证有效

<input [name]="field2" [id]="field2" ngModel #field="ngModel" required /> 

我使用了name和id属性中的field值。

验证动态字段

  manyFieldsValidators(form: any) {
    let fields: string[] = [];

    if (form && form.value) {
      for (let f of this.manyFields) {
        if (form.value[f] === '') {
          fields.push(f)
        } 
      } 
    }

    if (fields.length > 0) {
      return { fields: true, message: `${fields.join(',')} are empty` }
    } else {
      return { fields: false, message: '' }
    }

  } 

模板

    <div class="errorMsg" *ngIf="manyFieldsValidators(f).fields">
        {{manyFieldsValidators(f).message}}
    </div>

stackblitz demo

  

模板形式仅用于简单形式,您可以考虑使用Form Array

通过反应形式reactive form以更简洁的方式进行验证