本文为阅读官方文章 ngClass 的记内容。
在网页中,时常会出现当使用者点及某个按钮,或者,滑入某个区域的时候,某个指定元素的 css 样式会被改变,那这个时候,就很适合利用 ngClass
来动态加入指定的 class,进而达到这种需要动态改变目标元素的 css 样式的效果
ngClass 可以加入以下几种内容,来当作要为目标元素加入的 className 的内容
--- app.component.html ---
<h2 [ngClass]="'first second'">Title</h2>
--- app.component.css ---
.first {
color: red;
}
.second {
font-size: 30px;
}
上面的范例,可以为 h2 的标签中加入 first 和 second 这两个 class 所含有的 css 样式。
Note:
要注意,在 [ngClass]="" 的双引号里面,还有写入两个单引号,之後,才将欲加入的 className 写在单引号里面。
[ngClass]
里面--- app.component.html ---
<h2 [ngClass]="['first', 'second']">Title</h2>
--- app.component.css ---
.first {
color: red;
}
.second {
font-size: 30px;
}
第二种写法,在该元件中先定义一个阵列成员,里面放入想要加入的 className,最後,再将这个阵列绑到 [ngClass] 中
--- app.component.html ---
<h2 [ngClass]="title">Title</h2>
--- app.component.ts ---
export class AppComponent {
title = ['first', 'second'];
}
--- app.component.css ---
.first {
color: red;
}
.second {
font-size: 30px;
}
这个第二种写法,我们可以动态地为这个 title 阵列,加入新的元素,进而加为目标元素入相对应的 className。
--- app.component.ts ---
export class AppComponent {
isAdd = false;
}
--- app.component.css ---
.first {
color: red;
}
.second {
font-size: 30px;
}
--- app.component.html ---
<h2 [ngClass]="{'first': isAdd}">Title</h2>
<button (click)="isAdd = !isAdd">Switch</button>
上面的范例,我们可以透过按下按钮,来切换 isAdd 属性的 true 或 false,进而去影响 first 这个 className 是否会被加入到 h2 标签中。
藉此,我们就可以动态地决定是否要为目标元素加入特定的 className 了。
现在来看看如果,目标元素本身就含有 class 的时候,当动态加入 className 的话,会不会把原本就存在的 class 给清除掉罗?!
--- app.component.ts ---
export class AppComponent {
isAdd = false;
}
--- app.component.css ---
.first {
color: red;
}
.second {
font-size: 30px;
}
--- app.component.html ---
<h2 class="first" [ngClass]="{'second': isAdd}">Title</h2>
<button (click)="isAdd = !isAdd">Switch</button>
结果如下
结果是会直接再被加入到 className 中,而且原本就存在的 class 也会被保留住。
这边做个总结,
[ngClass]
我们可以动态地加入想要加入的 class 到指定元素的 className 中。
<<: Day1 Sideproject(作品集) from 0 to 1 -简介
今天来直接上手开始我们的 Google Apps Script 之旅啦! 我们在使用 Google ...
因为我这边群组团购机器人会用到的一些模板,所以在这篇文章介绍一下Template message,本...
Agenda 资安宣言 测试环境与工具 学习目标 技术原理与程序码 References 下期预告 ...
大家好,我是YIYI,今天我要来制作日记部分的介面。 如何进入日记页面? 日记的部分是点选像是笔的i...
主题描述 以下三个函数功能相同,都是把 base64 转换为 ArrayBuffer 测试看看哪个效...