*ngIf

このエントリーをはてなブックマークに追加

NgIfはテンプレート内で条件式を記述するためのディレクティブです。

NgIfの基本的な利用の仕方

NgIfを利用する場合は*ngIfをテンプレート内で記述し、値として判定に利用したプロパティを指定します。

@Component({
  selector: 'app',
  template: `
    <button type="button" (click)="show=!show">{{show ? 'hide' : 'show'}}</button>
    <div *ngIf='show'>show</div>
  `
})
export class App {
  show: boolean = true;
}

このように指定することでshowプロパティがtrueの場合のみdivが表示されるようになります。

Else文

以下のように指定を行うとelse文が指定できます。

@Component({
  selector: 'app',
  template: `
    <button type="button" (click)="show=!show">{{show ? 'hide' : 'show'}}</button>
    <div *ngIf='show; else elseBlock'>show</div>
    <ng-template #elseBlock>
        <div>hide</div>
    </ng-template>
  `
})
export class App {
  show: boolean = true;
}

elseの後にElseブロックで利用したいラベル名、今回は「elseBlock」を指定して<ng-template>に「#elseBlock」の指定を行います。

注意する点は、else時に<ng-template>が表示されるのではなく、<ng-template>内の要素が<div *ngIf=’…’>と差し替えられる点です。そのため<ng-template>はページ内の何処に記述しても問題ありません(ただ、一般的に<div *ngIf=’…’>の直後に指定を行います)

then文

以下のように指定を行うとthen文が指定できます。

@Component({
  selector: 'app',
  template: `
    <button type="button" (click)="show=!show">{{show ? 'hide' : 'show'}}</button>
    <div *ngIf='show; then thenBlock'>show</div>
    <ng-template #thenBlock>
    <div>thenBlock show</div>
    </ng-template>
  `
})
export class App {
  show: boolean = true;
}

thenの後にThenブロックで利用したいラベル名、今回は「thenBlock」を指定して<ng-template>に「#thenBlock」の指定を行います。

else文とは異なり<div *ngIf=’…’>の内容は表示されれず、<ng-template>内の要素が<div *ngIf=’…’>と差し替えられて表示されます。

さらに、TemplateRefで直接thenブロックの内容を指定することができます。

下記のサンプルではthenBlockAボタンをクリックされた際に#thenBlockAの内容を、#thenBlockBをクリックされた際に#thenBlockBの内容をthenブロックに挿入するように指定を行なっています。

@Component({
  selector: 'app',
  template: `
    <button type="button" (click)="thenBlock=thenBlockA">thenBlockA</button>
    <button type="button" (click)="thenBlock=thenBlockB">thenBlockB</button>
    <div *ngIf='show; then thenBlock'>show</div>
    <ng-template #thenBlockA>thenBlockA</ng-template>
    <ng-template #thenBlockB>thenBlockB</ng-template>
  `
})
export class App {
  thenBlock: TemplateRef<any> = null;
  show: boolean = true;
  @ViewChild('primaryBlock')
  thenBlockA: TemplateRef<any> = null;
  @ViewChild('secondaryBlock')
  thenBlockB: TemplateRef<any> = null;
}

オブジェクトの判定

オブジェクトの指定の後に?を付与することでオブジェクトが存在する場合のみオブジェクトへのアクセスを試みオブジェクトが存在しない場合でもエラーがでなくなります。

@Component({
  selector: 'app',
  template: `
    <p>{{obj1?.prop1}}</p>
    <p>{{obj2?.prop2}}</p>
  `
})
export class App {
  obj2:{} = {
    prop2:"prop2"
  }
}

上記の指定ではobj1オブジェクトへのアクセスをテンプレート内で行なっておりますが、obj1が存在しないため無視されて次のステートが実行されます。

非同期で情報を扱う場合はasyncパイプを追加して判定を行います。下記のサンプルではユーザー名が指定されている場合のみ出力を行なっております。

@Component({
  selector: 'app',
  template: `
    <button (click)="nextUser()">Next User</button>
    <br>
    <div>
      {{(userObservable|async)?.last}}, {{(userObservable|async)?.first}}
    </div>
    <ng-template #loading let-user>Waiting... (user is {{user|json}})</ng-template>
  `
})
export class App {
  userObservable = new Subject<{first: string, last: string}>();
  first = ['John', 'Mike', 'Mary', 'Bob'];
  firstIndex = 0;
  last = ['Smith', 'Novotny', 'Angular'];
  lastIndex = 0;
  nextUser() {
    let first = this.first[this.firstIndex++];
    if (this.firstIndex >= this.first.length) this.firstIndex = 0;
    let last = this.last[this.lastIndex++];
    if (this.lastIndex >= this.last.length) this.lastIndex = 0;
    this.userObservable.next({first, last});
  }
}

これは以下のようにngIfのasyncパイプを利用して以下のように記述することも可能です。

@Component({
  selector: 'app',
  template: `
    <button (click)="nextUser()">Next User</button>
    <br>
    <div *ngIf="userObservable | async as user">
      {{user.last}}, {{user.first}}
    </div>
  `
})
export class App {
  userObservable = new Subject<{first: string, last: string}>();
  first = ['John', 'Mike', 'Mary', 'Bob'];
  firstIndex = 0;
  last = ['Smith', 'Novotny', 'Angular'];
  lastIndex = 0;
  nextUser() {
    let first = this.first[this.firstIndex++];
    if (this.firstIndex >= this.first.length) this.firstIndex = 0;
    let last = this.last[this.lastIndex++];
    if (this.lastIndex >= this.last.length) this.lastIndex = 0;
    this.userObservable.next({first, last});
  }
}

記述パターン

NgIfディレクティブでは*ngIfを利用する方法以外にtemplate属性を利用する方法や<ng-template>を利用する方法が用意されています。

<div *ngIf="condition">ok</div>
<div template="ngIf condition">ok</div>
<ng-template [ngIf]="condition"><div>ok</div></ng-template>

参考URL

NgIf - ts - API

登録日 : 2017年05月03日 最終更新日 : 2017年5月5日

同じカテゴリー(@angular/common)のエントリー

検索

スポンサードリンク

バージョン

リファレンス