Javascript Angular 2.0 和 ng 风格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32300431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:51:31  来源:igfitidea点击:

Angular 2.0 and ng-style

javascriptangular

提问by Yaniv Efraim

I am building an Angular 2.0 component and I want to control it's style dynamically (using ng-style). After a quick view on Angular 2's docs i tried this:

我正在构建一个 Angular 2.0 组件,我想动态控制它的样式(使用ng-style)。在快速查看 Angular 2 的文档后,我尝试了以下操作:

<div class="theme-preview" ng-style="{'font-size': fontSize}">
  {{fontSize}}
</div>

And saw that the size is actually printed inside the div but did not affected the style. fontSizeis one of component's property bindings', meaning the component gets it from its parent like this:

并看到尺寸实际上是在div内部打印的,但并没有影响样式。fontSize是组件的属性绑定之一,这意味着组件从其父级获取它,如下所示:

<my-component [font-size]="size" />

While inside the component I have:

在组件内部时,我有:

@Component({
  selector: 'XXX',
  properties: ['fontSize']
})

Am I missing something here?

我在这里错过了什么吗?

回答by Eric Martinez

Update

更新

People still reach this answer, so I've updated the plnkr to beta.1. Two things have changed so far

人们仍然得到这个答案,所以我已经将 plnkr 更新为 beta.1。到目前为止,有两件事发生了变化

  • NgStyle is no longer necessary to be explicitly added in directives property. It's part of the common directives that are added by default.
  • The syntax has changed, now it must be camel case.
  • 不再需要在指令属性中显式添加 NgStyle。它是默认添加的通用指令的一部分。
  • 语法已更改,现在必须是驼峰式大小写。

Example

例子

@Component({
  selector : 'my-cmp',
  template : `
    <div class="theme-preview" [ngStyle]="{'font-size': fontSize+'px'}">
   {{fontSize}}
  </div>`
})
class MyCmp {
  @Input('font-size') fontSize;
}

@Component({ 
  selector: 'my-app',
  directives: [MyCmp],
  template: `
    <my-cmp [font-size]="100"></my-cmp>
  `
})

See this plnkr(Updated to beta.1)

请参阅此plnkr(已更新至 beta.1

回答by nir

For specific style, you can also use this:

对于特定样式,您还可以使用此:

<div class="theme-preview" [style.font-size]="fontSize+'px'">

回答by d1jhoni1b

Something like this is actually working on latest version of angular right now 4, the syntax actually changed, please notice the [ngStyle]

像这样的东西现在实际上正在处理最新版本的 angular 4,语法实际上发生了变化,请注意[ngStyle]

.color-box {
    width: 10px;
    height: 10px;
    display: inline-block;
}

<div class="color-box" [ngStyle]="{'background-color': your.model.object.color_code}"></div>