Angular2 ngIf-else [英] Angular2 ngIf-else

查看:3462
本文介绍了Angular2 ngIf-else的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图加载pictureA或pictureB。
我的第一个解决方案是这样的:

 < img * ngIf =my_picturesrc ={{my_picture }width =180height =80> 
< img * ngIf =default_picture&&!my_picturesrc ={{default_picture}}>

但我想在API-Reference上使用if-else ...:

 < div * ngIf =condition; else elseBlock> ...< / div> 
< ng-template#elseBlock> ...< / ng-template>

所以我这样做:

 < div * ngIf =my_picture; else elseBlock> 
< img src ={{my_picture}}>
< / div>
< ng-template#elseBlock>
< img src ={{default_picture}}>
< / ng-template>

但是我得到一个很大的异常堆栈:


  zone.js:388未处理的承诺拒绝:模板解析错误:
无法绑定到'ngIfElse',因为它不是已知的'div'属性。 (
- >

< div [ERROR - >] * ngIf =my_picture; else elseBlock>
< img src ={{ my_picture}}):UserComponent @ 15:13
属性绑定ngIfElse未被嵌入式模板上的任何指令使用。确保属性名称拼写正确并且

所有指令都列在@ NgModule.declarations中。(
- >

  [错误 - >]< div * ngIf =my_picture; else elseBlock> 
< img src ={{my_picture}}width =180height =8):UserComponent @ 15:8
'ng-template'不是已知元素


如何依赖简单的if-else块?

解决方案

你应该使用ng-template

 < ng-template#loading>做错了什么......< ; / NG-模板> 
< div * ngIf =userObservable; else loading;>
Aravind在这里
< / div>
< button(click)=userObservable =!userObservable>点击以切换< / button>
< / div>

LIVEDEMO


i'am trying to load pictureA or pictureB. My first solution is like this:

 <img *ngIf="my_picture" src="{{my_picture}}" width="180" height="80" >
 <img *ngIf="default_picture && !my_picture" src="{{default_picture}}">

But i would like use if-else like on API-Reference:

<div *ngIf="condition; else elseBlock">...</div>
<ng-template #elseBlock>...</ng-template>

So i do it like this:

 <div *ngIf="my_picture; else elseBlock">
     <img src="{{my_picture}}" >
 </div>
 <ng-template #elseBlock>
      <img src="{{default_picture}}" >
 </ng-template>

But i get a big exception-stack:

zone.js:388 Unhandled Promise rejection: Template parse errors:
Can't bind to 'ngIfElse' since it isn't a known property of 'div'. ("
        -->

        <div [ERROR ->]*ngIf="my_picture; else elseBlock">
            <img src="{{my_picture}}"): UserComponent@15:13
Property binding ngIfElse not used by any directive on an embedded template. Make sure that the property name is spelled correctly and

all directives are listed in the "@NgModule.declarations". (" -->

        [ERROR ->]<div *ngIf="my_picture; else elseBlock">
            <img src="{{my_picture}}" width="180" height="8"): UserComponent@15:8
'ng-template' is not a known element

How can i reliaze simple if-else block?

解决方案

You should be using ng-template

<ng-template #loading>Failed to do something wrong...</ng-template>
<div *ngIf="userObservable;else loading;">
  Aravind is here
</div>
   <button (click)="userObservable = !userObservable">Click to toggle</button>
</div>

LIVEDEMO

这篇关于Angular2 ngIf-else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆