0

I have my original working code from angular1 as following:

<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>

When I try to convert it into angular2 code following:

<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>

I get Can't have multiple template bindings on one element. Use only one attribute named 'template' or prefixed with * error. I have created a pipe called limitTo.

How to fix this error?

Thinker
  • 5,326
  • 13
  • 61
  • 137

1 Answers1

3

The error is because of you are using ngFor and ngIf on same element in angular2 you can use either one of them on single element for this the angular2 provides <template> directive to iterate over elements below code will be working.

<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> is depreciated in angular 4 so you can use <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>
Babar Hussain
  • 2,917
  • 1
  • 17
  • 14