angular从0到1:样式(css)的使用(上)
0.前言
写代码最讨厌的一件事就是写css,真的是难啊。不过还是要写,这篇文章主要记录angular中样式的不同写法。具体演示的是[ngclass]。本文为了表示更加清除,没有使用template模板
1.引用css文件(最原始方法)
TS文件:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.scss']
})
export class MenuComponent implements OnInit {
constructor() {
}
ngOnInit(): void {
}
}
HTML文件
<div class="top">
<div class="left" >
<img src="http://www.petsnet.cn/wp-content/uploads/2017/01/e76bc1db5286ebad2b8a5e3489fe1586.jpg" alt="二哈">
</div>
</div>
CSS文件
.top{
margin-top: 30px;
text-align: center;
height: 800px;
width: 800px;
}
.left{
margin-left: 15px;
height: 600px;
}
img{
width: 500px;
height: 400px;
}
效果:
2.ngClass绑定
在angular可以使用angular内置的ngClass命令。但是百度了一下加上自己的尝试,还有其他不同的表示
第一种: 格式:
[ngClass]="{'class': true}"
[ngClass]="{ CSS类名01:布尔类型,CSS类名:布尔类型 }"
//注意:对象的键最好用引号括起来,因为有的字符如果不用引号括起来就会报错
//注意:对象的键值如果有特殊字符就需要用引号括起来,否则会报错(PS: 最好都用引号括起来)
这个地方同步对比了ngClass和[ngClass], 因为我百度的结果发现好多人用的ngClass,
<div [ngClass]="{'style1': true}">
<p>床前明月光</p>
<p>疑是地上霜</p>
</div>
<div ngClass="style1">
<p>床前明月光</p>
<p>疑是地上霜</p>
</div>
CSS文件
.style1{
background-color: burlywood;
height: 200px;
width: 200px;
border: 1px solid;
}
.style2{
background-color: darkcyan;
height: 300px;
width: 300px;
border: 2px solid red;
}
运行结果:

第二种:可以动态改变 (优势所在)
HTML
<div [ngClass]="{'style1': isActive1,'style2':isActive2}">
<p>窗前明月光</p>
</div>
<button (click)="change()">给我变!</button>
CSS
.style1{
background-color: burlywood;
height: 50px;
width: 200px;
border: 1px solid;
margin:10px;
}
.style2{
background-color:chartreuse;
height: 50px;
width: 200px;
border: 1px solid;
margin:10px;
}
TS
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.scss']
})
export class MenuComponent implements OnInit {
isActive1=true
isActive2=false
constructor() {
}
ngOnInit(): void {
}
change(){
this.isActive2 =! this.isActive2;
this.isActive1 =! this.isActive1
}
}
运行结果:

第三种:三目表达式
HTML
<div [ngClass]=" isActive ? 'style1':'style2' ">
<p>窗前明月光</p>
</div>
<button (click)="change()">给我变!</button>
TS
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.scss']
})
export class MenuComponent implements OnInit {
isActive=true
constructor() {
}
ngOnInit(): void {
}
change(){
this.isActive =! this.isActive;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具