LoginSignup
2
0

More than 3 years have passed since last update.

Angularのテンプレート式で便利な存在演算子

Last updated at Posted at 2019-12-22

はじめに

Angularではコンポーネントのプロパティをテンプレートにバインディングするために{{...}}式を用います。

template-syntax.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-template-syntax',
  template: `
  <div>
      <h3>{{ title }}</h3>
  </div>
  `,
  styleUrls: ['./template-syntax.component.scss']
})
export class TemplateSyntaxComponent implements OnInit {

  title = "Angular Application";

  constructor() { }

  ngOnInit() {
  }

}

この式を使用する際の注意点や知っておくと便利かもしれない機能についてまとめます。

テンプレート式で利用できない演算子

  • 代入演算子
  • new 演算子
  • 連結を表す演算子
  • インクリメント、デクリメント演算子
  • ビット演算子

これらの演算子はテンプレート内部では使用できません。
試しに代入演算子を使用するとParser Errorが吐き出されます。

オブジェクトのプロパティにアクセスする

テンプレート式ではオブジェクトのプロパティにアクセスすることができます。

template-syntax.components.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-template-syntax',
  template: `
  <div>
      <h3>{{ title }}</h3>
      <p>{{ person.name }}</p>
  </div>
  `,
  styleUrls: ['./template-syntax.component.scss']
})
export class TemplateSyntaxComponent implements OnInit {

  title = "Angular Application";

  person = {
    name: 'hoge',
    age: 30
  };

  constructor() { }

  ngOnInit() {
  }

}

ブラウザ上にはpersonオブジェクトのnameプロパティのvalueである'hoge'が表示されます。

知っておくと便利かもしれない存在演算子

上記の構文を使用する際、personオブジェクトがundefinedの場合、コンソールにエラーが吐き出されます。

こんな時にいちいちオブジェクトのチェックをしてプロパティにアクセスするのは冗長なので存在演算子を使用するとすっきりします。

template-syntax.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-template-syntax',
  template: `
  <div>
      <h3>{{ title }}</h3>
      <p>{{ person?.name }}</p>
  </div>
  `,
  styleUrls: ['./template-syntax.component.scss']
})
export class TemplateSyntaxComponent implements OnInit {

  title = "Angular Application";

  // person = {
  //   name: 'hoge',
  //   age: 30
  // };

  constructor() { }

  ngOnInit() {
  }

}

「person?.name」の部分が存在演算子に該当します。これをやっておけばテンプレート側でオブジェクトの存在チェックをやってくれるので、コンポーネントがすっきりと書けます。

利用頻度は高くないかもしれませんが、知っておくと便利だと思います。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0