2

I'm setting the background-color of a div to be updated dynamically by assigning the style.background-color property like below..

<div [style.background-color]="cellColor">
  <span>{{ cellColor }}</span>
</div>

In its typescript file I assigned a default color which is set successfully. Later on I'm changing the value of the property "cellColor" by subscribing to a Subject inside the ngOnInit() life cycle of the component file like below.

Inside the Service definition.

@Injectable()
export class StyleService {
  editClicked = new Subject();
  constructor() { }
}

From another component I'm pushing new value for the "cellColor" property like this.

this.styleService.editClicked.next('white');

Then I'm subscribing to the Subject from my component's ts file like this.

ngOnInit() {
    this.styleService.editClicked.subscribe(
      (color : string) => {
        this.cellColor = color;
        console.log(this.cellColor);
      }
    )
  }

The property was successfully updated, although the view did not update. I'm already binding my div's style property using the [] brackets as shown above, then why wouldn't the view update? Am I missing something here?

However, for the same example if I subscribe using an Observable the property is changed and the view also gets updated.

ngOnInit() {
     Observable.of(true)
      .delay(2000)
      .subscribe((success) => {
        if(success){
          console.log('Pretend loading: success!');
          this.cellColor = 'white';
          this.cdr.markForCheck();
        }
      });
}

Why would it work when subscribing to an Observable but not to a Subject?

Pottermon
  • 73
  • 2
  • 8

0 Answers0