[Angular] 笔记 5:ngClass

本文详细介绍了Angular中的ngClass指令如何在HTML中动态添加或移除CSS类,包括字符串、数组和对象语法的使用示例,以及在实际组件中的应用,如根据Pokémon属性显示cool-bool类。
摘要由CSDN通过智能技术生成

Angular 中的 ngClass 是什么?
chatgpt 回答:
在Angular中,ngClass 是一个内置的指令,用于动态地添加或移除 HTML 元素的 CSS 类。它允许你根据条件设置一个或多个 CSS 类,可以是对象、数组或字符串。

使用方式:

  1. 字符串语法
<div [ngClass]="'class1 class2'">...</div>

在这个例子中,class1class2 类将被添加到 div 元素中。

  1. 数组语法
<div [ngClass]="['class1', 'class2']">...</div>

使用数组语法可以添加多个类到元素中。

  1. 对象语法
<div [ngClass]="{'class1': condition1, 'class2': condition2}">...</div>

基于条件动态地添加或移除类。如果 condition1trueclass1 类将被添加到元素中;如果 condition2trueclass2 类将被添加到元素中。

  1. 使用方法调用
<div [ngClass]="getClassNames()">...</div>

getClassNames() 是一个在组件中定义的方法,用于返回需要应用的类名。

ngClass 是一个非常有用的指令,能够根据组件中的变量或条件动态地管理元素的样式类,让你可以根据特定的情况或状态来改变元素的外观和行为。


Youtube tutorial:
app.component.ts:

// 类型检查
interface Pokemon {
  id: number;
  name: string;
  type: string;
  isCool: boolean;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  pokemons: Pokemon[] = [
    {
      id: 1,
      name: 'pikachu',
      type: 'electric',
      isCool: false,
    },
    {
      id: 2,
      name: 'squirtle',
      type: 'water',
      isCool: true,
    },
    {
      id: 3,
      name: 'charmander',
      type: 'fire',
      isCool: true,
    },
  ];

  constructor() {}
}

app.component.html,但是没有使用 ngClass 设置 CSS,而是使用属性绑定语法,动态添加 cool-bool CSS 类到 td 元素中。

<table>
  <thead>
    <th>Index</th>
    <th>Name</th>
    <th>Type</th>
  </thead>
  <tbody>
    <tr *ngFor="let pokemon of pokemons; let i = index">
      <td [class.cool-bool]="pokemon.isCool">{{ i }}</td>
      <td>{{ pokemon.name }}</td>
      <td>{{ pokemon.type }}</td>
    </tr>
  </tbody>
</table>

app.component.css

.cool-bool {
	/* 蓝色 */
    background: #0094ff;
}

可以看到如下的界面:

在这里插入图片描述
使用 ngClass 对象语法:
app.component.html:

<table>
  <thead>
    <th>Index</th>
    <th>Name</th>
    <th>Type</th>
  </thead>
  <tbody>
    <tr *ngFor="let pokemon of pokemons; let i = index">
      <td [class.cool-bool]="pokemon.isCool">{{ i }}</td>
      <td>{{ pokemon.name }}</td>
      <td>{{ pokemon.type }}</td>
    </tr>
    <tr *ngFor="let pokemon of pokemons; let i = index">
      <td [ngClass]="{'cool-bool':pokemon.isCool}">{{ i }}</td>
      <td>{{ pokemon.name }}</td>
      <td>{{ pokemon.type }}</td>
    </tr>
  </tbody>
</table>

Web 页面:
在这里插入图片描述

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值