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

效果

posted on   longkui  阅读(613)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示