在网格的子组件中设置选定的值。角2+

时间:2019-06-13 23:42:42

标签: angular typescript angular-ngselect angular8

使用Angular 8和TypeScript。 我有一个包含许多内部组件的网格,其中一个是<ng-select/>

数据绑定在子组件的OnInit中完成。 加载数据初始化后,我会看到所有值,并且过滤器正在按预期方式工作,但未显示为选定项。外观看起来像是在AAA-绿色行中所示。一旦我触摸并释放下拉菜单,就会选择适当的值。

gird select component

父组件代码:

 <clr-dg-cell>
    {{staffedReferral?.agency?.displayName}}
    <span>
      <app-agency-rep-select 
        [agencyId]=staffedReferral?.agency?.id 
        [selectedAgencyRepId]=staffedReferral?.agencyRepId
        (change)="changeAgencyRep($event, staffedReferral)">
      </app-agency-rep-select>
    </span>
  </clr-dg-cell>

选择组件代码:

import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Store } from '@ngrx/store';

import { IAgencyRep } from '@core/model';
import { RootStoreState, AgencyRepStoreSelectors, AgencyRepStoreActions } from '@app/_root-store';
import { AgencyRepDataService } from '@core/api/agency-rep-data.service';


@Component({
  selector: 'app-agency-rep-select',
  template: `
    <ng-select
      [loading]="isLoading$ | async"
      [ngModel]="_agencyRep"
      [items]="reps"
      (ngModelChange)="onChange($event)"
      (open)="onOpen()"
      [placeholder]="placeholder || 'Agency Reps...'"
      bindLabel="fullName"
    >
    </ng-select>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AgencyRepSelectComponent implements OnInit {
  @Output() change: EventEmitter<IAgencyRep> = new EventEmitter();
  @Input() placeholder?: string;
  @Input() selectedAgencyRepId?: number;
  @Input() agencyId?: number;

  reps: IAgencyRep[] = [];
  _agencyRep: IAgencyRep;
  error$: Observable<string>;
  isLoading$: Observable<boolean>;

  constructor(private store$: Store<RootStoreState.State>, private dataService: AgencyRepDataService) {
  }

  ngOnInit(): void {
    this.dataService.getAgencyRepsByAgencyId<IAgencyRep[]>(this.agencyId)
      .subscribe(
        (data) => {
          data.forEach(d => d.fullName = d.user.firstName + ' ' + d.user.lastName);
          this.reps = data;
          if (this.selectedAgencyRepId) {
            this._agencyRep = data.find(d => d.id === this.selectedAgencyRepId);
          }
        }
      );
  }

  onOpen() {
  }

  onChange(agencyRep) {
    if (!agencyRep) {
      agencyRep = { id: null };
    }
    this.change.emit(agencyRep);
  }

}

1 个答案:

答案 0 :(得分:0)

问题出在changeDetection。它应该是默认值,而不是OnPush changeDetection:ChangeDetectionStrategy。默认