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

来源:互联网 发布:易语言自动打码源码 编辑:程序博客网 时间:2024/05/13 22:48

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简介

原创粉丝点击