Search code examples
angulartypescriptangular-ngselectangular8

Set selected value in the sub component in the grid. Angular 2+


Using Angular 8 and TypeScript. I have a grid with a number of internal components, one of them is <ng-select/>

Data binding is done OnInit in the child component. When data is loaded initialized I see all the values and filter is working as expected, but it doesn't appear as a selected item. Visually it looks like it is shown in AAA - Green row. As soon as I touch and release dropdown, the proper value selected.

gird select component

Parent component code:

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

Select component code:

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

}

Solution

  • The problem was with changeDetection. it should be Default, not OnPush changeDetection: ChangeDetectionStrategy.Default