无底洞手游
76.49MB · 2025-12-01
使用ngClass和ngStyle可以进行样式的绑定。
ngStyle 根据组件中的变量, isTextColorRed和fontSize的值来动态设置元素的颜色和字体大小
<div [ngStyle]="{'color': isTextColorRed ? 'red': 'blue','font-size': fontSize + 'px'}"> This text has dynamic styles based on component variables.</div>import { Component, OnInit } from '@angular/core';@Component({ selector: 'app-cn06-class-and-style', templateUrl: './cn06-class-and-style.component.html', styleUrls: ['./cn06-class-and-style.component.css']})export class Cn06ClassAndStyleComponent implements OnInit { isTextColorRed: boolean = false; fontSize: number = 16; constructor() { } ngOnInit(): void { }}效果如下所示
<div [ngClass]="{'highlight': isHighlighted, 'error': hasError}"> This text has dynamic classes based on component variables.</div>import { Component, OnInit } from '@angular/core';@Component({ selector: 'app-cn06-class-and-style', templateUrl: './cn06-class-and-style.component.html', styleUrls: ['./cn06-class-and-style.component.css']})export class Cn06ClassAndStyleComponent implements OnInit { isHighlighted: boolean = true; hasError: boolean = false; constructor() { } ngOnInit(): void { }}效果如下所示
<div [ngStyle]="{'color': textColor, 'font-size': fontSize + 'px'}">This text has dynamic styles.</div><div [ngClass]="{'highlight': isHighlighted, 'error': hasError}">This text has dynamic classes.</div>通常情况下,你可以根据实际需求选择使用 ngStyle 或 ngClass 来实现动态样式。如果需要直接设置一些具体的样式属性,使用 ngStyle 更合适;如果需要根据条件来添加或移除类,使用 ngClass 更合适。在某些情况下,你也可以将两者结合起来使用,以实现更复杂的样式需求。