在角度模板中解析数组 [英] parse Array in angular template

查看:55
本文介绍了在角度模板中解析数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人使用不带集合的ngFor时可能会遇到某种情况,但似乎每个人都喜欢设置array的变量并让*ngFor绑定,如以下代码所示:

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:

数组

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

当您要运行5次或10次并且需要设置新的变量然后可以进行迭代时,它对模板并不友好,所以我想在模板中使用Array new Array,但它没有工作.无论new Array()还是使用关键字Array的任何关键字,它都会解析我们的变量,而不解析指定的关键字.

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.

错误日志

错误TypeError:_co.Array不是函数

ERROR TypeError: _co.Array is not a function

现在,我使用复杂的方法来解决这种情况:

Now I use the complex way to solve this situation:

模板

<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()"

推荐答案

AFAIK Angular在模板中不支持Array构造函数.

AFAIK Angular doesn't support Array constructor in template.

要解决此问题,您可以尝试以下操作:

To work around it you could try the following:

仅模板解决方案

1)[].constructor(10)

2)String.prototype.repeat()

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

3)使用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)使用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>

在组件上声明数组属性

您还可以在组件上创建Array属性:

You can also create Array property on your component:

export class AppComponent  {
  Array = Array;
}

然后

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

Stackblitz Example

您总是可以创建自己的管道:

And you can always create your own pipe:

另请参见

这篇关于在角度模板中解析数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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