Angularのテンプレート式で便利な存在演算子
7011 ワード
はじめに
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」の部分が存在演算子に該当します。これをやっておけばテンプレート側でオブジェクトの存在チェックをやってくれるので、コンポーネントがすっきりと書けます。
利用頻度は高くないかもしれませんが、知っておくと便利だと思います。
Author And Source
この問題について(Angularのテンプレート式で便利な存在演算子), 我々は、より多くの情報をここで見つけました https://qiita.com/kenya-112163/items/0e64bc6c46eb540f030d著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .