Search code examples
htmlangularangular2-changedetectionangular-ivy

Template Check not happening/Change detector not running (Angular)


Change Detection is not running in my Angular template for some reason. I am trying to change the color of the first div based on text change in second div(textbox). Here is what the code looks like:

<div [ngStyle]="{'background-color': titleText.innerText? 'red' : 'blue' }">Title</div>
<div style="border:1px solid black" contenteditable="true" aria-multiline="true" role="textbox" ngDefaultControl #titleText></div>

At runtime, when I enter some text into the textbox, the color of the first div does not change to red. However, before compiling if I pass some text to the div, then red is shown at runtime, again removing the text from the textbox does not change the color. I feel template check is not happening.

Here is the link to the repo: https://github.com/enzup/dummy/blob/master/src/app/app.component.html

I've set 'fullTemplateTypeCheck' to true under 'angularCompilerOptions' in tsconfig.json, tried installing multiple projects, used different angular versions (8,9,10,11) but none of them seem to work. But try uncommenting the code in app.component.ts file in ngAfterViewInIt() and the first div starts changing its color based on text change in the second div just fine, except the change is triggered every 5000ms (which is the time passed in setInterval()). Maybe the change detection is forcing template check?

Here is another repo that I cloned from stackblitz: https://github.com/enzup/angular-ivy-oghnan/blob/master/src/app/app.component.html

The template is the same as in the first repo. But here everything is working fine. I'm not sure why is it happening. I've compared both the repos, their tsconfig.json, angular.json, package.json, but nothing is out of order or is different. Please help me understand why the first repo does not produce the desired results and the second repo does it perfectly fine.

PS. I know there are workarounds to change the background color of the div other than the one I'm currently trying to follow, but it is not what I'm after, ngClass isn't working either(in the first repo only, in the second it is again working fine). I want to understand WHY the first repo is behaving erratically, while the second one is not.


Solution

  • You forgot to import FormsModule in app.module. By the way are you sure you understand custom controlValueAccessors as you seemed to have used ngDefaultControl. I would suggest you to read why controlValue accessors are needed. Also template type checking has nothing to do with change detection(Its just for type checking your html bindings.)