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 2022-01-31 16:27  longkui  阅读(571)  评论(0编辑  收藏  举报

导航