如何使用 Angular 从 TypeScript 方法绑定 css 样式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46445134/
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-10-21 04:56:02  来源:igfitidea点击:

How to bind css style from TypeScript method with Angular

angulartypescript

提问by Luki

I have a component like this below:

我有一个像下面这样的组件:

@Component({
  selector: 'app-car-item',
  templateUrl: './car-item.component.html',
  styleUrls: ['./car-item.component.css'],
})
export class CarItemComponent {
  public style: string

  addStyle() {
    this.style = 'font-size: 20px'
  }

How can I implement addStyle()method to change size of font in car-item.component.css?

如何addStyle()在 car-item.component.css 中实现更改字体大小的方法?

回答by tommueller

This is not how you do it in Angular! This is how you would do it:

这不是你在 Angular 中的做法!你会这样做:

In your CarItemComponentadd a vairable for the font-size for example:

在您CarItemComponent为字体大小添加变量中,例如:

fontSize: number;

In your addStyle()set this number to the font size you want to use and in your template add this to the element which's font-size you want to change:

在您addStyle()将这个值设为您要使用且模板中添加这哪是你想改变字体大小,元素的字体大小:

[style.font-size.px]="{{ fontSize }}"

回答by prampe

This could be useful (Angular 6):

这可能很有用(Angular 6):

  1. Change styles in order to look like disabled
  2. Eliminate the href
  1. 更改样式以使其看起来像残疾人
  2. 消除href

https://stackblitz.com/edit/angular-wzgr4h

https://stackblitz.com/edit/angular-wzgr4h