1

在这个 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");
       }
}
4

1 回答 1

1

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

这解决了错误并使required验证工作

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

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

验证动态字段

  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 演示

模板表单用于简单表单,可以通过Form Array您可以考虑使用的反应式表单以更简洁的方式完成验证reactive form

于 2018-08-09T03:23:23.373 回答