Stack Underflow
Stack Underflow

Reputation: 2453

Binding background color to ng2-avatar component

I have an ng2-avatar component with a background color bound to a property of my component. The background color is initially set correctly but will not update when my component's background color property is changed. It seems like this is a bug with the ng2-avatar component but it's possible I am doing something wrong. How can I get the avatar background color to update when the color attribute updates?

component.html

<avatar [background]="bg"></avatar>
<button (click)="c()">Change</button>

component.ts

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

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    bg = '#000000';

    c() {
        console.log('before: ' + this.bg);
        this.bg = '#' + (Math.floor(Math.random() * 900000) + 100000).toString();
        console.log('after: ' + this.bg);
    }
}

Full code on GitHub

Upvotes: 0

Views: 663

Answers (1)

SiddAjmera
SiddAjmera

Reputation: 39432

Apparently you'll have to call the ngOnInit on the avatar component once you change the config on it:

import { Component, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  bg = '#000000';

  @ViewChild('avatar') private elAvatar: any;

  c() {
    console.log('before: ' + this.bg);
    this.bg = '#' + (Math.floor(Math.random() * 900000) + 100000).toString();
    console.log('after: ' + this.bg);
    this.elAvatar.ngOnInit();
  }
}

And in the template:

<avatar #avatar [background]="bg"></avatar>
<button (click)="c()">Change</button>

That's what they've done in this Demo here:

Upvotes: 2

Related Questions