[英]Angular - Subscribe to changes in child components with @ViewChildren
I have these children components 我有这些孩子组件
<app-organization-item *ngFor="let organization of rows" [organization]="organization"></app-organization-item>
Inside this components, I have multiple select boxes with multiple values. 在此组件内部,我有多个带有多个值的选择框。
Something like this: 像这样:
<div class="col-xs-12" *ngIf='availableOrganizations.length > 0'>
<select [ngModel]="organization" (ngModelChange)="onChange($event)" [compareWith]="compareFn">
<option *ngFor="let org of availableOrganizations" [ngValue]='org' id="{{org.organization_id}}">{{org.name}}</option>
</select>
</div>
And: 和:
onChange(value) { this.organization = value; }
How can I get the values of all the components inside the parent component? 如何获取父组件中所有组件的值? (without using @Output).
(不使用@Output)。
Using @ViewChildren
inside the parent component won't work: 在父组件中使用
@ViewChildren
无效:
@ViewChildren(OrganizationItemComponent) components: QueryList<OrganizationItemComponent>
and 和
ngAfterViewInit() {
this.components.changes.subscribe(() => {
this.stuff = this.components.toArray();
console.log(this.stuff);
});
}
Nothing will show up when I change the select box inside de children component. 当我更改de children组件内的选择框时,什么都不会显示。 What am I doing wrong?
我究竟做错了什么?
You can use service to set the communication between them. 您可以使用服务来设置它们之间的通信。
import { Injectable, Inject } from '@angular/core';
import { Observable, Subject } from 'rxjs';
export interface OrderElement {
index: number,
item: any
}
@Injectable()
export class OrganizationsService {
organizations: OrderElement[] = [];
organizationsStream = new Subject();
constructor(
) {
}
setNewValue(itemIndex, object) {
let i = this.organizations.findIndex(element => element.index === itemIndex)
if(i >= 0 ) {
this.organizations[i].item = object;
} else {
this.organizations.push({index: itemIndex, item: object, oldValue: undefined})
}
this.organizationsStream.next(this.organizations);
}
getStream() {
return Observable.from(organizationsStream).startWith(organizations);
}
}
In constructor parent: 在构造函数parent中:
constructor(
private organizationsService: OrganizationsService
) {
this.organizationsService.getStream().subscribe(element => {
//You got all value
)
}
In template set: 在模板集中:
<app-organization-item *ngFor="let organization of rows; index as i;" [organization]="organization" [serviceToCall]="organizationsService" [index]="i"></app-organization-item>
In OrganizationItemComponent set: 在OrganizationItemComponent中设置:
@Input() public serviceToCall;
@Input() public index: number;
onChange(value) {
this.organization = value;
this.serviceToCall.setNewValue(index, value);
}
Remember to unsubscribe Observable and set provider for service. 请记住退订Observable并设置服务提供者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.