Привязка цвета фона к компоненту ng2-avatar - PullRequest
0 голосов
/ 17 сентября 2018

У меня есть компонент ng2-avatar с цветом фона, связанным со свойством моего компонента. Цвет фона изначально установлен правильно, но не будет обновляться при изменении свойства цвета фона моего компонента. Кажется, что это ошибка с компонентом ng2-avatar, но возможно я что-то делаю не так. Как получить цвет фона аватара для обновления при обновлении атрибута цвета?

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);
    }
}

Полный код на GitHub

1 Ответ

0 голосов
/ 18 сентября 2018

Очевидно, вам придется вызывать ngOnInit на компоненте аватара после изменения конфигурации на нем:

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();
  }
}

И в шаблоне:

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

Эточто они сделали в этой демонстрации здесь :

...