Check out this plunk showcasing an Angular form with a single input field and an array of input fields. Validation is needed to ensure that none of these fields are left empty.
The validation for the single field is working as expected, but I'm encountering issues when trying to validate the array of fields. An error
Error: Cannot assign to a reference or variable!
is appearing when the form is displayed. Any suggestions on how to resolve this issue in the plunk example?
@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");
}
}