版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.youkuaiyun.com/u011127019/article/details/78720520
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>