The initial update of the view does not occur when a component property changes in Angular 2 RC6

I am currently facing an issue with a component in my project. This component calls a service to retrieve locally stored JSON data, which is then mapped to an array of objects and displayed in the component view. The problem I am encountering is that the view bindings do not update properly the first time the service is called, but they do update correctly on subsequent calls.

Below is the template code for the component:

@Component({
    selector: 'list-component',
    template: `
        <button type="button" (click)="getListItems()">Get List</button>
        <div>
            <table>
                <tr>
                    <th>
                        ID
                    </th>
                    <th>
                        Name
                    </th>
                    <th>
                        Job Title
                    </th>
                </tr>
                <tr *ngFor="let employee of _employees">
                    <td>
                        {{employee.id}}
                    </td>
                    <td>
                        {{employee.name}}
                    </td>
                    <td>
                        {{employee.jobTitle}}
                    </td>
                </tr>
            </table>
        </div>
    `,
    changeDetection: ChangeDetectionStrategy.Default
})

Here is the controller class code for the component:

export class ListComponent {

    _employees: Employee[];

    constructor(
        private employeeService: EmployeeService
    ) {

    }

    getListItems() {
        this.employeeService.loadEmployees().subscribe(res => {
            this._employees = res;
        });
    }
}

And here is the code for the service:

@Injectable()
export class EmployeeService {

    constructor(
        private http: Http
    ) { }

    loadEmployees(): Observable<Employee[]> {
        return this.http.get('employees.json')
         .map(res => <Employee[]>res.json().Employees);
    }
}

Some approaches I have tried so far include changing the ChangeDetectionStrategy to OnPush and making the _employees property an observable. Despite trying various methods, the issue persists.

If anyone notices anything incorrect in my code or is aware of any potential RC6 issues that could be causing this behavior, please let me know. Thank you!

Answer №1

I encountered a similar issue and have yet to find a definitive solution. However, I found that using the detectChanges method worked for me. Below is a workaround that may help, but please keep in mind that it is not a perfect fix.

export class ListComponent {

_employees: Employee[];

constructor(
    private employeeService: EmployeeService,  private chRef: ChangeDetectorRef
) {

}

getListItems() {
    this.employeeService.loadEmployees().subscribe(res => {
        this._employees = res;
        this.chRef.detectChanges()
    });
}

}

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

Troubleshooting: Why is my ng serve command in Angular 5 not

Whenever I try to run ng serve, an error pops up ng : The term 'ng' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is ...

I am facing difficulty in retrieving data from Firestore using Angular

I've been utilizing the AngularFireList provided by @angular/fire/database to retrieve data from firestore. However, despite having data in the firestore, I am unable to fetch any information from it. import { Injectable } from '@angular/core&apo ...

Optimal technique for adding elements to the DOM using ngFor

My application features a websocket connected to an ngFor loop that populates data from approximately 100 records. Each entry in the list has a button with a click event attached, triggering the creation of a loading spinner via a 'div' element w ...

Enhancing Angular2 with setInterval

I'm having trouble with using setInterval in Angular 2. When I call a function, an error is displayed. My goal is to update the page data using AJAX and setInterval. export class AppComponent{ objMonitoring: Monitoring = new Monitoring(); arrMo ...

When I interact with a button in a series of buttons, all buttons undergo a change simultaneously rather than just the selected one -Angular

I'm having trouble updating the text inside a button upon clicking In my HTML, I have a list of buttons displaying angular material components: <table *ngIf="buildingImageList.length 0" mat-table [dataSource]="buildingImageList" class="mat-elevat ...

Incorrectly selecting an overload in a Typescript partial interface can lead to errors

My attempt to define an overload for my function using a Partial interface overloading is causing typescript to select the incorrect overload interface Args { _id: string; name: string; } interface Result { _id: string; name: string; } function my ...

The Ins and Outs of Selecting the Correct Module to Attach a Controller in NestJS CLI

My experience with NestJS has been great so far, especially the Module system and how easy it is to parse requests. However, I have a question about the NestJS CLI. Let's say I have multiple modules. When I create a controller using the command "nes ...

Creating a dropdown menu in Bootstrap 5 without using any of the Bootstrap

In my Angular application, I have a header with icons and pictures that I would like to use as dropdown menus. The code snippet for this functionality is shown below: <li class="nav-item dropdown"> <a class="nav-li ...

Removing buttons from a table row dynamically

Below is how I am adding the Button to Element: (this.sample as any).element.addEventListener("mouseover", function (e) { if ((e.target as HTMLElement).classList.contains("e-rowcell")) { let ele: Element = e.target as Element; let ro ...

Efficiently loading data in a table with a universal filter feature using Angular with PrimeNG

Recently, I managed to set up a datatable with the functionalities of both Lazy loading and global filter. Utilizing PrimeNG components for this implementation was a breeze. However, an issue surfaced where the global filter ceased to function when lazy lo ...

Loading screen displayed while transitioning between routes within Angular

I have been struggling to implement a loading spinner in my project. How can I display a loading screen when changing routes in Angular? Here is the HTML code snippet: <div *ngIf="showLoadingIndicator" class="spinner"></div> ...

What is the optimal method for defining a JSON serialization format for a TypeScript class?

Currently, I am in the process of developing a program using Angular and TypeScript. Within this program, there is a specific class named Signal that consists of various properties: export class Signal { id: number; obraId: number; obra: string ...

After sending an HTTP Post request in Angular 5, users are required to click in order

Currently, I am in the process of developing an Angular 5 component that integrates "ngx-file-drop" and "ngx-spinner" modules. Upon uploading a file through my API, an issue arises. Despite the successful upload of the file and the console.log message disp ...

Ensure that all content is completely loaded before displaying it using Angular 2

As an Angular developer, I am facing a challenge in my component where I am generating an image through a service HTTP call. Unfortunately, the image generation process takes longer than the site load time, causing the image to not appear immediately on th ...

What is the best way to prevent URL modification in Angular?

Currently, I am working on a project with a specific page (let's call it localhost:XXXX/notification-page) and we want this to be the only URL that can be accessed. Any attempt to change the URL should redirect users back to the notification-page. As ...

Implement TypeScript to include type annotations on functions' parameters using destructuring and the rest syntax

Issues with Typing in Typescript Trying to learn typing in Typescript has presented some difficulties for me: I am struggling to convert this code into a strongly-typed format using Typescript. const omit = (prop: P, { [prop]: _, ...rest}) => rest; ...

Typescript custom react hook - toggling with useToggle

I developed a custom hook to toggle boolean values: import { useState } from 'react'; export function useToggle(initialValue: boolean) { const [value, setValue] = useState<boolean>(initialValue); const toggleValue = () => setValue ...

Resizing a d3 graph for various screen resolutions

Looking to create a dynamic dashboard in Angular, I found a code snippet for a gauge chart at this link. Here is an example of how my HTML file appears: <div fxLayout="row" fxLayoutAlign="space-around center" > <div fxFlex='33%'> ...

Sending a POST request in Angular5 using the HTTP module

Angular 5 Attempting to create a function that will generate a resource on my API using Angular has proven to be a challenge. The "employee.service.ts" file contains a method named "saveEmployee" which is triggered by a function called "addEmployee" locate ...

What is the best way to include an item in a list with a specific identifier using the useState Record data type in a React application built with TypeScript?

Here is the structure of my Record type: const PEOPLE_MAP_INIT: Record<string, Person[]> = { "1": [], "2": [], "3": [] }; I have initialized the useState like this: const [PEOPLE_MAP, SET_PEO ...