Angular-订阅@ViewChildren的儿童组件的变化



我有这些孩子组件

<app-organization-item *ngFor="let organization of rows" [organization]="organization"></app-organization-item>

在此组件内,我有多个选择框,具有多个值。

类似的东西:

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

和:

onChange(value) { this.organization = value; }

如何获得父组件内所有组件的值?(不使用@Output(。

在父组件内使用@ViewChildren无法使用:

@ViewChildren(OrganizationItemComponent) components: QueryList<OrganizationItemComponent>

ngAfterViewInit() {
     this.components.changes.subscribe(() => {
       this.stuff = this.components.toArray();
       console.log(this.stuff);
    });
}

当我更改儿童组件内的选择框时,什么都不会显示。我在做什么错?

您可以使用服务来设置它们之间的通信。

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);
     }
}

在构造函数父母中:

constructor(
   private organizationsService: OrganizationsService
  ) {
     this.organizationsService.getStream().subscribe(element => {
       //You got all value
    )
  }

在模板集中:

<app-organization-item *ngFor="let organization of rows; index as i;" [organization]="organization" [serviceToCall]="organizationsService" [index]="i"></app-organization-item>

在组织ItemComponent中:

 @Input() public serviceToCall;
 @Input() public index: number;
 onChange(value) { 
   this.organization = value; 
   this.serviceToCall.setNewValue(index, value);
 }

记住要取消订阅可观察的服务和设置服务提供商。

最新更新