Stories

Detail Return Return

Angular: 樣式綁定 - Stories Detail

解決方案

使用ngClassngStyle可以進行樣式的綁定。

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 {
  }

}

效果如下所示
image

ngClass

<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 {
  }

}

效果如下所示
image

ngClass與ngStyle的區別

  1. ngStyle:
  • 用途:用於動態設置元素的內聯樣式。
  • 語法:[ngStyle]="{'property': value}",其中 property 是 CSS 樣式屬性,value 是要設置的樣式值。可以傳入一個對象,對象的鍵是樣式屬性,值是樣式值。
  • 示例:
<div [ngStyle]="{'color': textColor, 'font-size': fontSize + 'px'}">This text has dynamic styles.</div>
  • 注意:ngStyle 可以動態設置多個樣式屬性,適用於需要根據組件中的變量或邏輯來動態改變樣式的情況。
  1. ngClass:
  • 用途:用於根據條件動態添加或移除 CSS 類。
  • 語法:[ngClass]="{'class-name': condition}",其中 class-name 是 CSS 類名,condition 是一個布爾表達式,如果為 true,則添加該類,如果為 false,則移除該類。
  • 示例:
<div [ngClass]="{'highlight': isHighlighted, 'error': hasError}">This text has dynamic classes.</div>
  • 注意:ngClass 可以根據組件中的變量或邏輯來動態添加或移除類,適用於根據條件來改變元素的樣式。

通常情況下,你可以根據實際需求選擇使用 ngStyle 或 ngClass 來實現動態樣式。如果需要直接設置一些具體的樣式屬性,使用 ngStyle 更合適;如果需要根據條件來添加或移除類,使用 ngClass 更合適。在某些情況下,你也可以將兩者結合起來使用,以實現更復雜的樣式需求。

Add a new Comments

Some HTML is okay.