Home > front end >  Why property binding to the color of a text element is not reactive in angular?
Why property binding to the color of a text element is not reactive in angular?

Time:01-10

Below is my .ts file,

import { Component } from '@angular/core';

@Component({
  selector: 'app-event-binding',
  templateUrl: './event-binding.component.html',
  styleUrls: ['./event-binding.component.css']
})
export class EventBindingComponent {

  textColor = '';
  onInput = (ev: any) => {
    this.textColor = ev.target.value;
  }
}

Below is my HTML template ,

<div>
    <h3 [style.color]="textColor">EVENT BINDING</h3>
    <input type="text" (input)="onInput($event)">
</div>

Here when I completely type "blue" in the input box my text color of h3 changes to blue. But I noticed when i press backspace and now the value of textColor is "blu" , the text still remains in Blue color. I was expecting return to black. It changes to black only when I clear the entire input. So is there some kind of history retaining in the color in html? What does this?

CodePudding user response:

The same happens when maninpulating the DOM with plain JavaScript, I have prepared an example for you:

document.querySelector('input').addEventListener('input', event => {
  document.querySelector('h3').style.color = event.target.value;
})
<h3>EVENT BINDING</h3>
<input type="text">

When trying to set a value which the browser considers as invalid, the operation is not performed. You can see in the DOM that the value of the inline style is not updated. In this case, the last valid value will be used. Angular works the same than plain JavaScript here.

As a workaround, you can check whether the entered value is valid with CSS.supports(), and fall back to black:

onInput = (ev: any) => {
  const value = ev.target.value;
  this.textColor = CSS.supports('color', value) ? value : 'black';
}
  • Related