2017-07-28 63 views
0

我在我的主要成分下面的HTML:从ngFor环组件返回值

<app-loc-list-item *ngFor="let loc of locs; let i = index" [loc]="loc" [i]="i"></app-loc-list-item> 

LocListItemComponent看起来是这样的:

import { Component, OnInit, Input } from '@angular/core'; 

.... 

export class LocListItemComponent implements OnInit { 
    @Input() loc: Location; 
    @Input('i') index: number; 
    selected: boolean = false; 

    onLocationSelect() { 
    this.selected = !this.selected; 
    } 
} 

现在,可以有任意数量的那些小的组件之间以及0n之间的值可以为selected = true。我现在要为每个具有selected = true的组件接收index值。

如何访问这些索引值?

+0

你是否改变从LocListItemComponent中选择? –

+0

好的一点,我的确在编辑函数中这样做。这是一个简单的点击监听器。 – Spurious

回答

3

如果只想查询“应用程序-LOC-列表项的子女从父组件则包括在父这行代码

@ViewChildren(LocListItem) listItems: QueryList<LocListItem> 

这样你就可以遍历listItems属性在你的父母,看看哪些已被选中

+0

这听起来很有趣。我会试一试,看看我是否需要实现这一切。 – Spurious

+0

这是一个很好的答案。我喜欢它有多简单。有一点需要补充的是,我还需要导入组件。 – Spurious

1

对于您可以使用

@Output:用于从子组件的数据传递给父组件

父组件:

<app-loc-list-item *ngFor="let loc of locs; let i = index" [loc]="loc" [i]="i" (change)="selectChange($event)"></app-loc-list-item> 

selectChange(data) 
{ 
    console.log(data); 
} 

子组件:

export class LocListItemComponent implements OnInit { 
    @Input() loc: Location; 
    @Input('i') index: number; 
    @Output()change: EventEmitter<any> = new EventEmitter<any>(); 
    selected: boolean = false; 

    onLocationSelect() { 
    this.selected = !this.selected; 
    let data = { 'index' : this.index , 'selected' : this.selected } 
    this.change.emit(data); 
    } 
} 
+0

这个答案也适用,所以我提高了答案,但Dean的答案更短,需要的代码更少,尤其是对于孩子。感谢您的帮助,我也测试过您的作品,并且很有魅力。 – Spurious

+0

@疯狂,没问题,很高兴你找到了2个解决方案。 :) –

0

Angular中的组件之间没有双重数据绑定(即在AngularJs中)。

没有为你的问题的一些方式,一种方式是:

  • 使用服务,您定义的初始位置和你的孩子组件

您有:

this.yourServices.locs.splice(index, 1) 

编辑:我说的是不对的。这将是组件之间不相关的情况。

+0

我觉得像一个'服务'是一个矫枉过正。我不想为一个单一目的数组创建一个'service'。 – Spurious