Issue with "Encountered error while attempting to differentiate..."

Utilizing Angular4 along with PrimeNG has been my choice for development. To prevent template repetition in my HTML file, I opted to use the ng-container. However, upon implementing the ng-container, an error surfaced:

Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed

How can I effectively employ ng-container with the *ngFor directive to present data within a nested dataTable? Despite various attempts, access to this data seems unattainable.

This represents the structure of the JSON data:

{
"status": 0,
"dallases": [{
    "vehicle_id": 17954,
    "dallassettings": "3",
    "dallasupdated": "False",
    "dallas_list": [{
        "number": 666111222,
        "auth": 3
    }, {
        "number": 666777888,
        "auth": 4
    }, {
        "number": 123454321,
        "auth": 4
    }]
}
}

Service

export class VehicleService {
    private defUrl = 'dummy.url';

constructor(private http: Http) { }
getVehicle(username?: string, password?: string) {
    const url = (!username || !password) ? this.defUrl : 'dummy.url' + username + '/' + Md5.hashStr(password);
    return this.http.get(url)
        .map(res => res.json());

Component

export class VehicleComponent implements OnInit {

  cols: any[];

  ngOnInit() {
    this.cols = [
      { field: 'vehicle_id', header: "Vehicle ID" },
      { field: 'dallassettings', header: 'Dallas settings' },
      { field: 'dallasupdated', header: 'Dallas updated' },
      { field: 'dallas_list', header: 'Dallas list' }
    ];

  public vehicles: GeneralVehicle[];

  constructor(private vehicleService: VehicleService, private router: Router) {
    this.vehicleService.getVehicle().subscribe(vehicle => {
      this.vehicles = vehicle;
    });
  }

interface GeneralVehicle {
  status: number;
  dallases: Vehicle[];
}

interface Vehicle {
  vehicle_id: number;
  dallassettings: string;
  dallasupdated: string;
  dallas_list: DallasList[];
}

interface DallasList {
  number: number;
  auth: number;
}

Template

<div *ngIf="vehicles">
  <p-dataTable [value]="vehicles.dallases" expandableRows="true">
    <p-header>List of vehicles: <b>{{currentUser}}</b></p-header>
    <p-column expander="true" styleClass="col-icon"></p-column>
    <p-column field="vehicle_id" header="Vehicle ID" [sortable]="true"></p-column>
    <p-column field="dallassettings" header="Dallas settings" [sortable]="true"></p-column>
    <p-column field="dallasupdated" header="Dallas updated" [sortable]="true"></p-column>
    <ng-template let-vehicle pTemplate="rowexpansion">
      <ng-container *ngFor="let d of vehicles.dallas_list; let i = index; trackBy: trackByFunction">
        <p-dataTable [value]="d">
          <p-column field="number" header="Number" [sortable]="true"></p-column>
          <p-column field="auth" header="Auth" [sortable]="true"></p-column>
        </p-dataTable>
      </ng-container>
    </ng-template>
  </p-dataTable>
</div>

I aim to create a dataTable featuring expandable rows that open up into another dataTable, allowing users to manage data within the expanded row.

All functionality works perfectly until I trigger an expansion - at which point, the error emerges.

Your assistance is greatly appreciated!

Answer №1

It seems like there are some issues in your template that need attention. Take a look at the structure of your JSON data to identify any discrepancies. One specific path that stands out is:

vehicles.dallas_list

In this case, you can simplify by removing the ng-container and directly reference the vehicle (associated with let-vehicle) within the inner [value] to iterate through the dallas_list.

To enhance clarity, consider adjusting your template as follows:

<div *ngIf="vehicles">
  <p-dataTable [value]="vehicles.dallases" expandableRows="true">
    <p-column expander="true" styleClass="col-icon"></p-column>
    <p-column field="vehicle_id" header="Vehicle ID" [sortable]="true"></p-column>
    <p-column field="dallassettings" header="Dallas settings" [sortable]="true"></p-column>
    <p-column field="dallasupdated" header="Dallas updated" [sortable]="true"></p-column>
    <ng-template let-vehicle pTemplate="rowexpansion">
        <p-dataTable [value]="vehicle.dallas_list">
          <p-column field="number" header="Number" [sortable]="true"></p-column>
          <p-column field="auth" header="Auth" [sortable]="true"></p-column>
        </p-dataTable>         
    </ng-template>
  </p-dataTable>
</div>

Demo

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

Implementing TypeScript type declarations for merging core types

Is there a way to perform type declaration merging in TypeScript for built-in types when using imports? I am currently attempting to merge interfaces as per the guidelines outlined in this documentation: https://www.typescriptlang.org/docs/handbook/declar ...

A standard set of code used to manage various HTTP methods such as retrieving data, updating data, adding new

Previously in angularjs or angular-1, there was a shared code snippet to manage various http methods like GET, PUT, POST, DELETE, // Used for GET, PUT, POST, DELETE requests sharedService.process(method, url, data, headers).then(function(result){ / ...

Allow users to zoom in and out on a specific section of the website similar to how it works on Google Maps

I am looking to implement a feature on my website similar to Google Maps. I want the top bar and side bars to remain fixed regardless of scrolling, whether using the normal scroll wheel or CTRL + scroll wheel. However, I would like the central part of the ...

The process of invoking a function within another function in TypeScript Angular

Just starting out with Angular 2, I've written the following code in my Angular project: export class TestClass { constructor() { this.initMap(); } initMap() { this.marker.addListener('dragend', this.onMarkerDr ...

Resolving circular dependencies caused by APP_INITIALIZER

My AuthenticationService is responsible for loading the AngularFirestore and is loaded in the RootComponent. All app modules are lazily loaded within the RootComponent (which contains the main router-outlet). However, several sub-modules also load the Ang ...

Developing a dynamic object deserializer in TypeScript/Angular 2

My background is in C# where I have experience working in a dynamic and reflective manner. Now, I am transitioning to TypeScript for writing a class and trying to apply similar principles. To provide context, I am converting an existing application into a ...

The issue of flickering while scrolling occurs when transitioning to a new page in Angular

I have encountered an unusual issue in my Angular 13 + Bootstrap 5 application. When accessing a scrollable page on small screen devices, the scrolling function does not work properly and causes the page to flicker. I observed that this problem does not o ...

Checkbox offering a tri-state option

Seeking help on creating a checkbox with three states. I have implemented a method to toggle between these states upon clicking. However, the issue is that this method is only triggered after the HTML changes. As a result, the checkbox's navigation be ...

Using TypeScript to import the fs module

Although it may appear as a repeated question, none of the solutions I've come across seem to resolve the issue: Within my .ts file: import * as fs from 'fs'; // error: SyntaxError: Unexpected token * // OR import fs from 'fs'; / ...

Is there a way to retrieve the quantity of children from an element using protractor?

I am currently working with Protractor and I need to determine the amount of child components associated with a specific element. The element in question belongs to a table category. let table = element(by.css('#myTable')); My objective now is ...

What is the best way to create a memoized function in React?

I am currently developing an application using react and typescript, and I am facing a challenge in memoizing a function. const formatData = ( data: number[], gradientFill?: CanvasGradient ): Chart.ChartData => ({ labels: ["a", ...

Encountering a Problem with TypeScript Decorators

I've been diving into TypeScript by working on TS-based Lit Elements and refactoring a small project of mine. However, I'm starting to feel frustrated because I can't seem to figure out what's wrong with this code. Even though it' ...

Implementing the ternary operator on a nested object field in typescript to enforce type validation

Is there an issue with my code or is this intentional? I want to write something similar to this. type MyDefinition = { salutation: string; value?: { typeOfValue: string; val?: string }; }; function create(name: string, input?: Partial<MyDefin ...

Is it possible to integrate angular-bootstrap-datetimepicker with bootstrap3?

Looking for an accessible date picker solution for my project. The project is built on Bootstrap3, but the angular-bootstrap-datetimepicker has a dependency on Bootstrap4. Can I still integrate angular-bootstrap-datetimepicker with Bootstrap3? ...

Angular and Firestore, when combined, present a unique challenge as the queries

After upgrading the code of an outdated project to the latest versions of Angular and RxJs, I made every effort to update the code as thoroughly as possible. Here is a link to my previous code However, I am now encountering the issue of receiving undefin ...

Looking to build a library with Angular 5?

Is it possible to develop a library in Angular 5? Will this library be guaranteed to maintain compatibility with upcoming versions of Angular? ...

Allowing the OPTIONS method in CORS when sending a REST request from AJAX to a WCF Service

After spending 7 hours scratching my head, I am still unable to figure this out. Despite my extensive search on the web, no luck has come my way. My Angular App is sending requests to a WCF command-line hosted service application. To bypass CORS, I utilize ...

When attempting to run the yarn build dist command, an error of type TypeError is encountered, stating that it is not possible to set the constructor property

Upon executing the following command in a GitHub workflow, I encountered this error: npm-run-all -p types transpile @internal_package: $ swc src --out-dir dist @internal_package: /home/runner/work/repo-name/repo-name/node_modules/ttypescript/lib/loadTypesc ...

Filter an array of objects in Angular2 based on properties that are not included in the specified values

I'm encountering some difficulties while filtering an array of objects based on a specific set of values: Here is the array that needs to be filtered: const items: Product[] = ... values Next, I have created an array containing the products that I w ...

Can you explain the definition of const?

Can someone explain why it is necessary to include the keyword const in the following line of code while using angular2dart: directives: const [HeroDetailComponent] Thank you for clarifying this aspect of component properties. ...