2017-05-31 5 views
4

角度テンプレートでif-elseステートメントを作成したいと思います。私はそれを開始しました:ng-containerだけでif-else Angularテンプレートを作成するには?

<ng-container *ngIf="contributeur.deb; else newDeb" > 
    [... HERE IS A RESULT 1] 
</ng-container> 
<ng-template #newDeb> 
    [... HERE IS A RESULT 2] 
</ng-template> 

そして、私は唯一の使用NG-コンテナに試してみました:

<ng-container *ngIf="contributeur.deb; else newDeb" > 
    [... HERE IS A RESULT 1] 
</ng-container> 
<ng-container #newDeb> 
    [... HERE IS A RESULT 2] 
</ng-container > 

残念ながら、これは動作しません。私はこのエラーがあります:

ERROR TypeError: templateRef.createEmbeddedView is not a function 
    at ViewContainerRef_.createEmbeddedView (eval at <anonymous> (vendor.bundle.js:11), <anonymous>:10200:52) 
    at NgIf._updateView (eval at <anonymous> (vendor.bundle.js:96), <anonymous>:2013:45) 
    at NgIf.set [as ngIfElse] (eval at <anonymous> (vendor.bundle.js:96), <anonymous>:1988:18) 
    at updateProp (eval at <anonymous> (vendor.bundle.js:11), <anonymous>:11172:37) 
    at checkAndUpdateDirectiveInline (eval at <anonymous> (vendor.bundle.js:11), <anonymous>:10873:19) 
    at checkAndUpdateNodeInline (eval at <anonymous> (vendor.bundle.js:11), <anonymous>:12290:17) 
    at checkAndUpdateNode (eval at <anonymous> (vendor.bundle.js:11), <anonymous>:12258:16) 
    at debugCheckAndUpdateNode (eval at <anonymous> (vendor.bundle.js:11), <anonymous>:12887:59) 
    at debugCheckDirectivesFn (eval at <anonymous> (vendor.bundle.js:11), <anonymous>:12828:13) 
    at Object.eval [as updateDirectives] (ActionsButtons.html:5) 

このコードで何がうまくいかないのですか?

答えて

9

The code for the ngIf directiveは、ネストされたコンテンツを表示するためにcreateEmbeddedViewを呼び出すelseブランチのテンプレート(TemplateRef)への参照が渡される予定です。したがって、他の種類の要素をelseコンテンツに使用しようとするのは意味がありません。うまくいきません。ただし、必要に応じてng-containerng-templateにネストできます。

これは直感的に見えるが、structural directives(あなたが*と呼んすなわちもの)は関係なくそれらが結合している要素の種類、フードの下ng-templateとして表さない常にであることを念頭に置いてクマかもしれない - これらの二つのコードの断片が同じである:

<ng-container *ngIf="contributeur.deb; else newDeb" > 
    ... 
</ng-container> 
<ng-template #newDeb> 
    ... 
</ng-template> 

<ng-template [ngIf]="contributeur.deb; else newDeb"> 
    <ng-container> 
     ... 
    </ng-container> 
</ng-template> 
<ng-template #newDeb> 
    ... 
</ng-template> 
+0

私は、[角度のドキュメントのページ](https://angular.io/docs/ts/latest/guide/structural-directivesを読んでお勧めします.html)の構造指令に - 長いですが、本当に有益な情報です。 –

関連する問題