angular - Data Binding causes ExpressionChangedAfterItHasBeenCheckedError -
i'm new angular 4. have data binding field below. somehow, there expressionchangedafterithasbeencheckederror.
<form> <div> <h2>hello {{input.value}}</h2> <input type="text" [value]="input.value" name="inputtest"/> <input type="text" #input [value]="name"/> </div> <button type="submit">submit</button> </form> below simple constructor:
export class app { name:string; constructor() { this.name = `angular! v${version.full}` } } i read lot of posts error, still don't understand why simple data binding cause error.
i tried below code, doesn't work.
ngafterviewinit() { console.log("ngafterviewinit"); this.cd.detectchanges(); } please help!!
please refer plunker: https://plnkr.co/edit/16atvkgf2ba6z2ojqt6h?p=preview
as explained in everything need know change detection in angular 1 of operations angular performs dom update. includes both interpolations , bindings updates. angular performs these operations each dom in order found in template. these operations explained in the mechanics of dom updates in angular.
your template looks this:
<h2>hello {{input.value}}</h2> <input type="text" #input [value]="name"/> so angular starts updating dom , first performs update h2 element. evaluates {{input.value}} empty string since hasn't yet updated value binding on input. updates h2 hello , remembers empty string value. proceeds updating bindings input - [value]="name" , sets value angular! v4.3.1. change detection finished @ stage.
then runs verification stage described in everything need know expressionchangedafterithasbeencheckederror error. during verification stage angular evaluates {{input.value}} , compares previous value. since input has been processed expression evaluates angular! v4.3.1 different empty string used h2 element during change detection. error:
expression has changed after checked. previous value: ''. current value: 'angular! v4.3.1'.
it means if change order of elements in template see no error. works ok:
<input type="text" #input [value]="name"/> <h2>hello {{input.value}}</h2>
Comments
Post a Comment