微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

效果

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐