In this plunk I have an Angular form that contains one input field followed by an array of input fields. I need to validate that any of these fields is not empty.
The single field works well, but I'm struggling with validating the array of fields, I'm getting an error Error: Cannot assign to a reference or variable!
when the form is displayed. Any ideas how to fix the plunk attempt?
@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");
}
}
Error: Cannot assign to a reference or variable
error because[(ngModel)]="field2"
you can't assaignfield2
this solve the error and make the
required
validation workI have use the value of
field
from name and id attribute.validate dynamic fields
template
stackblitz demo