I am dynamically populating a table with inputs as:
<table>
<ng-container *ngFor="let cell of cells; let i = index;">
<tr>
<td>
<form class="number-form">
<mat-form-field class="number-full-width" style="height: 75px !important">
<mat-label>Number {{cell.value}}</mat-label>
<input matInput matNativeControl [(ngModel)]="cell.value" [formControl]="_number_form_control"/>
<mat-error *ngIf="_number_form_control.hasError('number') && !_number_form_control.hasError('required')">
Please enter a valid number
</mat-error>
<mat-error *ngIf="_number_form_control.hasError('required')">
A number is <strong>required</strong>
</mat-error>
</mat-form-field>
</form>
</td>
</tr>
</ng-container>
</table>
In the TS side:
export class CELLCLS {
value: number = 1.0;
}
@Component({
selector: 'app-my-work',
templateUrl: './my-work.component.html',
styleUrls: ['./my-work.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyWorkComponent {
public cells: CELLCLS[] = [];
public _number_form_control = new FormControl('', [Validators.required, Validators.pattern(/^-?(0|[1-9]\d*)?$/)]);
public _matcher = new MyErrorStateMatcher();
constructor(private cdRef:ChangeDetectorRef) {
}
ngAfterViewInit() {
this.cdRef.detectChanges();
}
}
Initially, when I first populated the cells, then the previous set value in cell.value will be reset to 1.0, and got the ExpressionChangedAfterItHasBeenCheckedError, then I added detectChanges, this error is gone, and I was able to avoid the error, but cell.value still gets reset to 1 when I pushed in a new cell. After I remove [formControl], then I am seeing the value gets updated and preserved. So I guess ngModel is conflicting with formControl in this case. What should I do if I want to keep formControl?