【问题标题】:Angular 2 dynamic style bindingAngular 2 动态样式绑定
【发布时间】:2017-05-27 11:00:13
【问题描述】:

我有以下 Angular 2 组件:

import { Component, Inject, Input } from '@angular/core';

@Component({
    selector: 'generic-component',
    templateUrl: 'generic-component.component.html',
    styleUrls : ['generic-component.component.css']
 })
 export class GenericComponentComponent{    
    @Input() backCol: string = "#F0F8FF";  
    @Input() divClass: string = "myClass";
    ...
 }

使用模板 html :

<div class={{divClass}} [style.backgroundColor]="backCol">
    This is a div
</div>

当应用程序启动时,模板使用默认的 backCol 十六进制颜色变量正确呈现 div。

但我想在之后将 backCol 变量字符串更改为另一种十六进制颜色,可能是在一个事件中。

父组件我有这样的东西:

@Component({
  template: `
    <generic-component divClass={{myComp.divClass}} [style.backgroundCol]="myComp.backCol">
    </generic-component>
   `
})
export class ParentComp{
  myComp = new GenericComponentComponent();
}
onColorChange(){
  this.myComp.divClass = "mySecondClass";
  this.myComp.backCol = "#A22B11";
}

但是新颜色没有渲染 onColorChange() 调用。所有其他属性绑定(如 divClass)都已正确更新和呈现。我做错了什么?

【问题讨论】:

  • myComp 应该是什么? this.backCol = "#A22B11"呢?
  • 它是 GenericComponentComponent 类的一个实例。我使用该实例将 GenericComponentComponent 渲染到父级的 html 模板中。
  • 或许this.instance.backCol = "#A22B11" 那么呢?如果不是,请提供更多关于myComp 是什么的信息(代码)
  • 编辑了我的问题。

标签: css angular binding


【解决方案1】:

以下不是获取子组件引用的正确方法

export class ParentComp{
  myComp = new GenericComponentComponent();
}

您需要使用@ViewChild 来获取对子组件的引用: 在您的父模板中:

<generic-component #child>
</generic-component>

此外,您不需要将类和样式作为输入传递。因为您可以使用 @ViewChild 获取对子属性的引用

在你的父组件中:

@Component({
  template: `
    <generic-component #child>
    </generic-component>
   `
})
export class ParentComp{

    @ViewChild('child') myComp;

    onColorChange(){
      this.myComp.divClass = "mySecondClass";
      this.myComp.backCol = "#A22B11";
    }
}

编辑: 使用 @ViewChildren 示例更新了 plunkr。 例子: https://plnkr.co/edit/a0zddtEe0Q3No4mfaKQZ?p=preview

【讨论】:

  • 如果我有一个子组件数组怎么办?我希望能够在父类中创建一个 GenericComponentComponent 数组。
  • 你可以使用@ViewChildren('child1','child2','child3') childList:QueryList;
  • 我想我现在明白了。我只绑定属性而不更新组件实例本身,这就是我无法更改样式的原因,对吗?谢谢!
猜你喜欢
  • 2017-07-05
  • 2017-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-13
  • 1970-01-01
  • 2018-02-02
相关资源
最近更新 更多