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