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

posted on 2022-01-31 12:59  longkui  阅读(202)  评论(0编辑  收藏  举报

导航