将背景颜色绑定到 ng2 头像组件



我有一个 ng2-头像组件,其背景颜色绑定到我的组件的属性。背景颜色最初设置正确,但在更改组件的背景颜色属性时不会更新。这似乎是 ng2-头像组件的错误,但我可能做错了什么。当颜色属性更新时,如何让头像背景颜色更新?

组件.html

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

组件.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 上的完整代码

显然,一旦更改了头像组件上的配置,就必须调用头像组件上的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>

这就是他们在此演示中所做的:

最新更新