您的位置:首页 > Web前端 > AngularJS

Angular 安全导航操作符(?.)和空属性路径

2017-12-05 15:14 162 查看
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简介
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: