2017-03-06 79 views
0

我有我原來的工作代碼angular1如下:Angular2多個綁定錯誤

<div align="center" ng-show="showWords" > 
    <div ng-repeat="word in whichArray | limitTo:limitToMain" ng-if="$index % 2 == 0" class="row"> 
     <div class="col" align="right" style="margin-right:1cm;"><h3>{{whichArray[$index]}}</h3></div> 
     <div class="col" align="left" style="margin-left:1cm;"><h3>{{whichArray[$index + 1]}}</h3></div>  
    </div> 
</div> 

當我嘗試將其轉換成angular2代碼如下:

<div align="center" *ngIf="showWords" > 
    <div *ngFor="let word of whichArray | limitTo:limitToPresent" *ngIf="$index % 2 == 0" class="row"> 
     <div class="col" align="right" style="margin-right:1cm;"><h3>{{whichArray[$index]}}</h3></div> 
     <div class="col" align="left" style="margin-left:1cm;"><h3>{{whichArray[$index + 1]}}</h3></div>  
    </div> 
</div> 

我得到Can't have multiple template bindings on one element. Use only one attribute named 'template' or prefixed with *錯誤。我創建了一個名爲limitTo的管道。

如何解決這個問題?

+0

Angular2不要有$指數其唯一指標 –

回答

3

錯誤是因爲你在angular2中的相同元素上使用ngFor和ngIf,你可以在單個元素上使用它們中的任何一個爲此,angular2提供<template>指令來遍歷代碼將工作的元素。

<div align="center" *ngIf="showWords" > 
    <template ngFor [ngForOf]="whichArray | limitTo:limitToPresent" let-item let-i="index"> 
    <div *ngIf="i % 2 == 0" class="row"> 
     <div class="col" align="right" style="margin-right:1cm;"><h3>{{whichArray[i]}}</h3></div> 
     <div class="col" align="left" style="margin-left:1cm;"><h3>{{whichArray[i + 1]}}</h3></div> 
    </div> 
    </template> 
</div> 

<template>在角4貶值,所以你可以使用<ng-template>

<div align="center" *ngIf="showWords" > 
    <ng-template ngFor [ngForOf]="whichArray | limitTo:limitToPresent" let-item let-i="index"> 
    <div *ngIf="i % 2 == 0" class="row"> 
     <div class="col" align="right" style="margin-right:1cm;"><h3>{{whichArray[i]}}</h3></div> 
     <div class="col" align="left" style="margin-left:1cm;"><h3>{{whichArray[i + 1]}}</h3></div> 
    </div> 
    </ng-template> 
</div> 
+0

感謝這個答案,它的工作! – Nitish

+0

在這裏你去:p! – Nitish

+0

歡迎伴侶:) –