The Safe Navigation Operator helps with preventing null-reference exceptions in component template expressions. It returns object property value if it exists or null otherwise.
<p> I will work even if student is null or undefined: {{student?.name}} </p>
Bonus
{{a?.b?.c}}
Underneath will be compiled to.
(_co.a == null)? null: ((_co.a.b == null)? null: _co.a.b.c));
file:app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
This code will generate an error:
<p> {{student.name}} </p>
This code will work correctly:
<p> {{student?.name}} </p>
`
})
export class AppComponent {
student: {name: string, otherProperties: any} | null = null
}
file:app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
imports: [BrowserModule],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule {}
翻译自:https://www.30secondsofcode.org/angular/s/safe-navigation-operator