Angular 安全导航操作符(?.)和空属性路径
发布时间:2020-12-17 08:35:43 所属栏目:安全 来源:网络整理
导读:Angular 的安全导航操作符(?.) 是一种流畅而便利的方式,用来保护出现属相路径中null和undefined值。 这种用法基本上和C#6.0中的委托触发操作符用法相同。 student?.name:当student不为空的时候输出name的值。 一、空属性路径 在Angular中 当前模块属性为空
Angular 的安全导航操作符(?.)是一种流畅而便利的方式,用来保护出现属相路径中null和undefined值。 这种用法基本上和C#6.0中的委托触发操作符用法相同。 student?.name:当student不为空的时候输出name的值。 一、空属性路径 在Angular中 当前模块属性为空时,输出空字符串,不会抛出异常 <div class="alert alert-info"> <p *ngIf="content">this is {{content}}</p> <p>测试内容</p> <p>this is {{content}}</p> </div> import { Component } from '@angular/core'; @Component({ selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; } 二、空对象路径 在Angular中 对象为空时抛出异常
解决方案1:使用 && 逻辑判断符 <p>对象为空:{{student&&student.name}}</p> 解决方案2:使用 *ngIf 判断指令 <p *ngIf="content">this is {{content}}</p> 解决方案3:使用?. 安全导航操作符(推荐) <p>对象为空2:{{student?.name}}</p>
更多: Angular2开发环境搭建之VS Code Angular CLI简介2 Angular CLI简介 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |