君は心理学者なのか?

大学時代に心理学を専攻しなぜかプログラマになった、サイコ(心理学)プログラマかろてんの雑記。

Angular2/4の*ngIfと[hidden]の使い分け/違い〜Component自体は削除せず非表示にするにはどうしたらよいか〜

結論

*ngIfを使うとComponent自体消えてしまうが、

[hidden]を使うと非表示になるだけでComponentはそのまま残る。

*ngIfの場合

<app-sample *ngIf="showFlg"></app-sample>

[hidden]の場合

<app-sample [hidden]="showFlg"></app-sample>

いきさつ

Angular2/4にて、こんなことがあった

  • 2つのComponentA、ComponentBがある

  • タブAがアクティブの時ComponentA、

    タブBがアクティブの時ComponentBが表示される

  • ComponentAの値の変化に応じて、ComponentBの値を変化させる

この時、はじめはこのように実装しようと思った。

初めに考えた方法

*ngIfを使って実装してみた。

<button (click)="onClick()">タブ切り替えボタン</button>
<app-a *ngIf="showFlg"></app-a>
<app-b *ngIf="!showFlg"></app-b>
export class AppComponent {
  public showFlg :boolean = true;

  /** タブ切り替えボタン */
  onClick() :void
  {
    this.showFlg = !this.showFlg;
  }
}

*ngIfの結果

f:id:karoten512:20171201004748g:plain

↑ DOMごと消えてしまっている

この方法だと、

ComponentAが表示されているときはComponentBが破棄されてしまっているので、

Serviceを通じてComponentBの値を操作することが出来ない。悲しい。

次に考えた方法

Componentを削除せずに、非表示にしたい。と思ったので「ngif compnent not destroy」で検索。

angular - Angular2: ngIf without destroying component - Stack Overflow

Q. Is there an angular2 blessed way 
    to hide a component without destroying the component?

A. The [hidden] property is what you are looking for.
    It more or less replaced ng-show / ng-hide in Angular2.

ありがとうstackoverflow。

以下のように[hidden]を使って実験してみる。

<button (click)="onClick()">タブ切り替えボタン</button>
<app-a [hidden]="showFlg"></app-a>
<app-b [hidden]="!showFlg"></app-b>

[hidden]の結果

f:id:karoten512:20171201005146g:plain

↑ hiddenが付くだけで、DOMとしては残っている

うまくComponentが消えずに残ってくれた!