angular中从0到1:条件语句ngIf、ngSwitch的使用
原文链接:这里
0.前言
angular中的if在,一种是 *ngIf=”expression” ,一般写在html中。这篇文章主要记录*ngIf的几种用法。
1. ngIf用法
1.1可以用作显示和隐藏
HTML
<div *ngIf="isShow" >
窗前明月光
</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 {
isShow=true
constructor() {
}
ngOnInit(): void {
}
change(){
this.isShow=!this.isShow
}
}
效果:

1.2可以和else搭配使用
HTML
<div *ngIf="isShow; else notShow ">
这是ture的情况
</div>
<ng-template #notShow>
<div>
这是false的情况
</div>
</ng-template>
<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 {
isShow=true
constructor() {
}
ngOnInit(): void {
}
change(){
this.isShow=!this.isShow
}
}
效果:

1. ngSwitch
HTML
<div>
<span [ngSwitch]="status">
<p *ngSwitchCase="1">
这是1的情况
</p>
<p *ngSwitchCase="2">
这是2的情况
</p>
<p *ngSwitchCase="3">
这是3的情况
</p>
<p *ngSwitchDefault>
这是4的情况(默认)
</p>
</span>
</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 {
status=1
constructor() {
}
ngOnInit(): void {
}
change(){
this.status++;
if(this.status==5)
this.status=1;
}
}
效果

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具