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

Luk*_*uki 5 typescript angular

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

@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'
  }
Run Code Online (Sandbox Code Playgroud)

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

tom*_*ler 5

这不是 Angular 中的做法!您将这样做:

在您CarItemComponent添加一个可变的字体大小,例如:

fontSize: number;
Run Code Online (Sandbox Code Playgroud)

在您的设置中addStyle(),将此数字设置为您要使用的字体大小,并在模板中将其添加到您要更改的字体大小的元素中:

[style.font-size.px]="{{ fontSize }}"
Run Code Online (Sandbox Code Playgroud)