Reputation: 121
I am working on a angular application with angular 7.0.4.
I want to set the focus on the first input element of the modal if my workingtimes list has more elements than 1 in it. The problem is if I open the modal it throws me this exception:
ModalComponent.html:23 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ng-untouched: true'. Current value: 'ng-untouched: false'.
at viewDebugError (core.js:16878)
at expressionChangedAfterItHasBeenCheckedError (core.js:16866)
at checkBindingNoChanges (core.js:16968)
at checkNoChangesNodeInline (core.js:19839)
at checkNoChangesNode (core.js:19828)
at debugCheckNoChangesNode (core.js:20432)
at debugCheckRenderNodeFn (core.js:20386)
at Object.eval [as updateRenderer] (ModalComponent.html:23)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:20375)
at checkNoChangesView (core.js:19729)
The error occurs on this lines of code in the modal.component.html file:
<input class="input" type="time" [(ngModel)]="time.From" [autofocus]="workingDay.Times?.length > 1">
The [autofocus] directive looks like this:
export class AutoFocusDirective implements OnInit{
@Input('autofocus') enabled: boolean = true;
constructor(
private element: ElementRef
) {
}
ngOnInit() {
if (this.enabled) {
(this.element.nativeElement as HTMLInputElement).focus();
}
}
}
I actually can not see the reason why this occures.
Thank you for your help on advance.
Upvotes: 2
Views: 541
Reputation: 86730
Try adding
(this.element.nativeElement as HTMLInputElement).focus();
this into setTimeOut
Sometimes binding will not occur as per what we think, and value changes are there in binding when during the digest cycle so in most of that cases this error occurred.
For more details refer -
Upvotes: 2