After adding a new user, the previous user inputs loses the disabled, the same happens with *ngFor="let user in users.slice().reverse()"
insted of unshift.
addUser() {
this.users.unshift({
id: 2,
email: '[email protected]',
checkbox: false,
disabled: false,
});
}
HTML:
<button mat-mini-fab (click)="addUser()">add</button>
<form #elementForm="ngForm" name="elementForm" >
<div *ngFor="let user of users; let i = index">
<mat-form-field appearance="outline" floatLabel="always">
<mat-label>Email {{ user.disabled }}</mat-label>
<input matInput type="email" name="email{{ i }}" [(ngModel)]="user.email [disabled]="user.disabled" />
</mat-form-field>
<mat-checkbox [(ngModel)]="user.checkbox" [name]="'checkbox' i [disabled]="user.disabled">Checkbox {{ user.disabled }}</mat-checkbox>
</div>
</form>
Everything works fine without form
Example: https://stackblitz.com/edit/angular-ivy-dqsyk9?file=src/app/app.component.html
CodePudding user response:
name attribute should be unique for input element. Create name attribute with unique id instead of index.
<form #elementForm="ngForm" name="elementForm" >
<div *ngFor="let user of users; let i = index">
<mat-form-field appearance="outline" floatLabel="always">
<mat-label>Email {{ user.disabled }}</mat-label>
<input
matInput
[disabled]="user.disabled"
type="email"
name="email{{ user.id }}"
[(ngModel)]="user.email"
/>
</mat-form-field>
<mat-checkbox
[disabled]="user.disabled"
[(ngModel)]="user.checkbox"
[name]="'checkbox' user.id"
>Email {{ user.disabled }}</mat-checkbox
>
</div>
</form>