parse Array in angular template

一个人想着一个人 提交于 2019-12-23 05:33:07

问题


somebody maybe encounter some situation when use the ngFor without collections.But seems looks like every one like to set the variable of array and let *ngFor binding like following code:

array

// typescript

public bignumber:number[]=[1,2,3,4,5,6,7,8,9,10]

//html

<ng-template *ngFor="let item of bignumber | index as i">
  p {{i}}
  <!-- would show ten times -->
</ng-template>

It's not friendly for template when you want to run 5 times or 10 times and you need to set the new varible then you can iterator.So I want to use Array new Array in template but it didn't work.No matter new Array() or any you would use the keyword Array, it would parse the our variable but not the specify keyword.

error log

ERROR TypeError: _co.Array is not a function

Now I use the complex way to solve this situation:

template

<ng-template [ngForOf]="[].map.call({length:10},[].map).fill('')" let-i="index">
  p {{i}}
  <!-- show 10 times -->
</ng-template>

Is any possible use the cleary code like:

[ngForOf]="Array(10).fill()"

回答1:


AFAIK Angular doesn't support Array constructor in template.

To work around it you could try the following:

Template only solutions

1) [].constructor(10)

2) String.prototype.repeat()

<ng-container *ngFor="let item of ' '.repeat(2).split(''), let i = index ">
  p {{i}}
</ng-container>

3) Using ngTemplateOutlet

<ng-container *ngTemplateOutlet="tmpl; context: { $implicit: 0 }"></ng-container>


<ng-template #tmpl let-i>
  <div>
    Your template here {{ i }}
  </div>
  <ng-container *ngIf="i < 10">
      <ng-container *ngTemplateOutlet="tmpl; context { $implicit: i + 1 }"></ng-container>
  </ng-container>
</ng-template>

3) Using NgIf

<ng-container *ngIf="1; then tmpl"></ng-container>

<ng-template #tmpl let-i>
  <div>
    Your template here {{ i }}
  </div>
  <ng-container *ngIf="i < 10">
      <ng-container *ngIf="i + 1, then tmpl"></ng-container>
  </ng-container>
</ng-template>

Declaring Array property on component

You can also create Array property on your component:

export class AppComponent  {
  Array = Array;
}

and then

<ng-container *ngFor="let item of Array.apply(null, Array(2)), let i = index ">
  p {{i}}
</ng-container>

<br>

<ng-container *ngFor="let item of Array(2).fill(), let i = index ">
  p {{i}}
</ng-container>

Stackblitz Example

And you can always create your own pipe:

See also

  • Repeat HTML element multiple times using ngFor based on a number


来源:https://stackoverflow.com/questions/47586525/parse-array-in-angular-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!