将背景颜色绑定到ng2-avatar组件

问题描述 投票:0回答:1

我有一个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的完整代码

angular property-binding
1个回答
2
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.