Assign a specific value to the sub-component within the grid using Angular 2+

Incorporating Angular 8 and TypeScript into my project, I have a grid that consists of various internal components, one being <ng-select/>.

The data binding takes place in the child component during onInit. Upon loading and initialization of the data, all values are displayed correctly, and the filter functions as expected. However, the selected item does not appear visually until I interact with the dropdown menu by clicking on it. Once I do this, the proper value is then selected.

https://i.sstatic.net/PfkwG.png

Code snippet from the parent 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>

Code snippet from the select component:

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

}

Answer №1

The issue lied in the changeDetection setting, which needed to be set to Default instead of OnPush. changeDetection: ChangeDetectionStrategy.Default

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to adding npm semver to an Angular project in Ionic

Currently, I am working on an Angular project that utilizes the Ionic framework. My goal is to employ Semvar to compare the local version with the API version in order to prompt users to update. Following the installation of semver: npm install semver I ...

What is the best way to pass a dynamically generated component as the ng-content for another dynamically generated component?

Need help with creating a modal for our library using viewRef.createComponent. I want to generate Component A and embed Component B inside it, utilizing <ng-content> to fetch content from Component B. Component A serves as the modal template, while ...

a guide to transforming data into a string with json using angular

I am struggling to figure out how to bind my form data into a JSON string. My situation involves using a string field in the database and saving checkbox values in a single database column using JSON. I have created an HTML form, but I am unsure of how to ...

Problems encountered when utilizing $in operator in Mikro ORM MongoDB operations

For my project, I'm utilizing mikro orm with MongoDB to handle database operations in TypeScript. So far, it has proven to be the most effective ORM for MongoDB in this language. However, I've encountered type errors when using $in with Object ID ...

A step-by-step guide for updating a minor version of Angular with Angular CLI

I've been searching online for the answer to this straightforward question, but can't seem to find it anywhere... In my angular 4 project (made with angular cli), I want to utilize the newly introduced http interceptors in version 4.3. Could so ...

Following the update, Angular no longer requires any node dependencies

Recently upgraded from Angular 5 to 9 and encountered an error in the browser's devtools: Uncaught ReferenceError: global is not defined After researching, I found a helpful post that discusses the issue: Upgrading to angular-6.x gives "Unca ...

Encountering issues with the enhanced Angular 16 application

Recently, I encountered an issue while upgrading my Angular 10 application to use Angular 16. Following the Angular Update Guide, I smoothly transitioned through the versions until reaching Angular 16. However, when running the "ng version" command in Visu ...

Using dynamic imports to enhance code by adding the `.at()` function can lead to errors in the process

Below is the content of my .tsconfig configuration file: { "compilerOptions": { "target": "es6", "baseUrl": "./src", "lib": ["dom", "dom.iterable", "esnext&q ...

How come the useEffect hook is causing re-rendering on every page instead of just the desired endpoint?

I am a novice attempting to retrieve data from a database and display it on the front-end using Axios, ReactJS, and TypeScript. My intention is for the data to be rendered specifically on localhost:3000/api/v1/getAll, but currently, it is rendering on all ...

JavaScript heap exhausted while running Docker container

Typically, I start my application by running npm run dev. The package.json file contains a script like the one below: "scripts": { "dev": "nodemon server.ts", } Everything is working fine in this setup. I have cr ...

Angular's getter value triggers the ExpressionChangedAfterItHasBeenCheckedError

I'm encountering the ExpressionChangedAfterItHasBeenCheckedError due to my getter function, selectedRows, in my component. public get selectedRows() { if (this.gridApi) { return this.gridApi.getSelectedRows(); } else { return null; } } ...

Encountering a MIME type error in Angular when refreshing the page or entering the path manually, but the issue does not occur

Currently facing a bit of a challenge here. I'm developing an Angular application and running into some issues with routing when it comes to path parameters. Within my Routes configuration, I have these paths defined (among others): { path: 'rev ...

One way to conceal different sections of a Chart.js chart is by clicking on the legend

When using ChartJS, clicking on the legend will make the section disappear. Is it possible to reverse this behavior? For example, when clicking on the legend, all sections in the chart except for the clicked one should disappear. Does anyone have a sugge ...

Guide to integrating global interfaces into your Nuxt project

Recently diving into the world of Nuxt 3, I've encountered a challenge while exploring TypeScript functionalities. My current goal is to create a versatile NavBar featuring multiple buttons with unique links. To achieve this, I aimed to establish an ...

Angular2 is throwing an error: "NavigationService provider not found! (MenuComponent -> NavigationService)"

I am in the process of developing an angular (beta7) application. I aim to have a MenuComponent at the top that utilizes the NavigationService to navigate throughout different sections of my app. To ensure that the NavigationService remains a singleton, I ...

Oops! An issue occurred while trying to compile the file constructor.d.ts in the common-behaviors folder of @angular/material/core. The error message received was: "error TS1005: ';'

Switching from Bootstrap to Angular Material caused an unexpected error when trying to run ng serve: Error: node_modules/@angular/material/core/common-behaviors/constructor.d.ts:14:64 - error TS1005: ';' expected. The errors encountered include: ...

Error encountered in Angular: Trying to assign a value to an empty string array results in the error message "Type (string | undefined)[] is not assignable to

Struggling with an issue in my Angular App - trying to assign a value to an empty array Current environment: node 12.18.4 npm 6.14.8 Here's my typescript.ts code snippet: import { Injectable } from "@angular/core"; import { Product } from ...

No overload error encountered with TypeScript function call

I am working on an async function that communicates with the backend and I need it to handle axios error messages. My goal is to display these messages in a form. export async function register( prevState: string | undefined, formData: FormData ) { t ...

What could be causing this TypeScript code to not pass typechecking?

defining two objects in TypeScript with different property sets and assigning them to each other. Link to more information ...

Using Angular Typescript with UWP causes limitations in accessing C# WinRT component classes

Currently, I am working on a UWP application built with Angular5 and I would like to incorporate Windows Runtime Component(Universal) classes into the application to access data from a table. import { Component,OnInit } from '@angular/core'; @C ...