【问题标题】:Angular 6+: Pass array name in ngFor from @inputAngular 6+:从@input 在 ngFor 中传递数组名称
【发布时间】:2019-10-20 16:58:37
【问题描述】:

我创建了一个列表组件,成功地通过一组项目运行并通过*ngFor 循环输出其数据。

现在我想重用这个组件并添加更多可能的数据数组以供选择。为此,创建了一个@input,允许我将数组名称“传递给”组件,无论它在哪里使用,但是当我尝试将它传递给*ngFor 时出现错误。

我的 ts 代码是:

@Input() listName : string;
list1: any = [
 {title: 'title1'},
 {title: 'title2'},
 {title: 'title3'},
]
list2: any = [
 {title: 'titlea'},
 {title: 'titleb'},
 {title: 'titlec'},
]

组件如下所示:

<app-listcomp listName="list1"></app-listcomp>

我认为这不是组件内部的正确语法:

*ngFor="let listItem of {{listName}}"

但无法退出找到通过@Input(或任何其他正确方式)传递数组名称的正确方法。

当我在 *ngFor 循环中使用特定的数组名称时,它当然可以完美运行。

【问题讨论】:

  • 如果listName是一个数组作为输入,那么它应该是*ngFor="let listItem of listName",也贴出组件代码。

标签: arrays angular ngfor let


【解决方案1】:

你可以这样做

类:

getList() {
  return this[this.listName];
}

模板:

*ngFor="let listItem of getList()"

【讨论】:

  • 呃...你传递了你想要检索的列表。是不是有点傻?
  • 是的,我知道,它是满足您要求的替代解决方案,因为您不能在 *ngFor 中进行插值
【解决方案2】:

有多种解决方案,但取决于全球环境和您真正需要的。

最简单的解决方法就是直接把期望的数组给组件。

在组件代码中:

@Input()
myList: any[];

在模板中:

*ngFor="let listItem of myList"

但是如果你真的需要它来工作,就像你在问题中提到的那样,只需使用一种方法。 当然,您需要传递按名称索引的数组的字典(或映射)。

在组件代码中:

@Input()
myLists: {[name: string]: any[]}; // dictionary of arrays indexed by name

getList(name: string): any[] {
   return this.myLists[name];
}

在模板中:

*ngFor="let listItem of getList('the name I want')"

编辑

从您编辑后我在您的问题中看到的内容,我可以给您一个更接近您期望的答案。

在组件代码中:

get selectedList(n): any[] {
   return this[this.listName];
}

在模板中:

*ngFor="let listItem of selectedList"

【讨论】:

  • 我已更新我的代码示例以获取有关我的问题的更多信息。如果可以,请在您的示例中参考它会很棒。
猜你喜欢
  • 1970-01-01
  • 2019-02-23
  • 2019-02-25
  • 1970-01-01
  • 2020-01-18
  • 1970-01-01
  • 2018-02-06
  • 1970-01-01
  • 2019-08-24
相关资源
最近更新 更多