3

I have the following HTML structure:

<input type="text" [(ngModel)]="styleObj.backgroundColor">
<div [ngStyle]="styleObj">change style of this div</div>

And js/ts:

styleObj = {
  backgroundColor: "black"
}

At first, it seems to work as expected. The bgColor of the div is black and whenever I type a valid value (example: "white") for the BgColor property via the input it updates just fine.

But the problem is that when I enter an invalid value, the ngStyle does nothing. It doesn't update/remove the old value.

Example: when I type "white" (valid) then change to "whitee" (invalid) the background stays white. I can go even further to let's say "whiteeblablabla" and it won't change. It'll only change when I enter a valid value for BgColor.

I'm using Angular 4.0.0. That didn't happen on Angular 1. I guess Angular validades the properties before actually making the changes for better performance. That behavior is good for some applications but in my case, where I want users to be able to enter their own value and get visual feedback, it doesn't make any sense.

Am I right about this? Is there a workaround/solution to this? Or I'm doing something wrong?

atcastroviejo
  • 253
  • 1
  • 3
  • 10
  • 2
    I think it works as expected. Try to set `div.style.background = 'blabla'` and you will see that style won't change https://jsfiddle.net/yurzui/f2gp4qzm/ – yurzui Apr 09 '17 at 13:27
  • 1
    You're right. It doesn't change. But I want it to change when I set "blabla" (invalid value). I don't want to have a "black" bgColor while my input is "blabla". When invalid, I want it to have no bgColor. Sorry if I wasn't clear enough – atcastroviejo Apr 09 '17 at 15:35

0 Answers0