Looking to retrieve a single data point from [object][object]

Presented here is an angular component:

import { Component, OnInit } from '@angular/core';
import { Hall } from 'src/app/models/hall.model';
import { HallService } from 'src/app/services/hall.service';
import { ActivatedRoute, Router } from '@angular/router';
import {City} from "../../models/city.model";

@Component({
  selector: 'app-halls-list',
  templateUrl: './halls-list.component.html',
  styleUrls: ['./halls-list.component.css']
})
export class HallsListComponent implements OnInit {
  Halls?: Hall[];
  currentHall: Hall = {};
  currentIndex = -1;
  name = '';
  placeqty='';
  //cityid='';
    cityid:any;

  constructor(private hallService:HallService,private route: ActivatedRoute,private router: Router) { }

  ngOnInit(): void {
    this.retrieveHalls();

  }

  retrieveHalls(): void {
    this.hallService.getAll()
      .subscribe(
        data => {
          this.Halls = data;
          console.log(data);
        },
        error => {
          console.log(error);
        });
  }

  refreshList(): void {
    this.retrieveHalls();
    this.currentHall = {};
    this.currentIndex = -1;
  }
  setActiveHall(hall: Hall, index: number): void {
    this.currentHall = hall;
    this.currentIndex = index;
  }

  deleteHall(): void {
    this.hallService.delete(this.currentHall.id)
      .subscribe(
        response => {
          console.log(response);
          this.router.navigate(['/halls']);
        },
        error => {
          console.log(error);
        });
  }
}

The component fetches data from a RESTful API implemented with Spring Boot. The "cityid" field in the returned object contains both the city's name and its ID like so:

[
    {
        "id": 1,
        "name": "TestHall",
        "placeqty": 100,
        "cityid": {
            "id": 2,
            "name": "Dnepr"
        }
    }
]

In this scenario, only one city is associated with each entry. The objective now is to display just the city's name without its ID. Below is the code snippet from the template:

<div class="col-md-6">
  <h4>Список залов</h4>
  <ul class="list-group">
    <li
      class="list-group-item"
      *ngFor="let hall of Halls; let i = index"
      [class.active]="i == currentIndex"
      (click)="setActiveHall(hall, i)"
    >
      {{ hall.name }}
     <br>
     кол-во мест:  {{ hall.placeqty }}
      <br>
     <p>{{hall.cityid | json}}</p>
      <div *ngFor="let item of hall.cityid | keyvalue;">

        {{ item.key}} - {{ item.value }}

      </div>

    </li>

  </ul>

</div>
<div class="col-md-6">
  <div *ngIf="currentHall.id">
    <h4>Зал</h4>
    <div>
      <label><strong>Название:</strong></label> {{ currentHall.name }}
      <label><strong>Количество мест:</strong></label> {{ currentHall.placeqty }}
      <label><strong>Город:</strong></label> {{ currentHall.cityid }}

    </div>


    <a class="badge badge-warning" routerLink="/cities/{{ currentHall.id }}">
      Изменить
    </a>
    <div *ngIf="!currentHall">
      <br />
      <p>Выберите Зал...</p>
    </div>
  </div>
</div>

If I were using PHP, I would simply do something like:

echo $cityid[0]['name'];

without any need for a loop. Is there a similar approach in Angular? Alternatively, how can this be achieved?

Here is my model class for Hall:

export class Hall {
  id?:any;
  name?:string;
  placeqty?:string;

  cityid?:string;

}

As a reference, below is also my City model which follows the same structure in Angular 12:

export class City {
  id?:any;
  name?:string;
}

Answer №1

If you want to collect all comments related to an answer...

Suppose you receive data like this:

{
    "id": 1,
    "name": "TestHall",
    "placeqty": 100,
    "cityid": {
        "id": 2,
        "name": "Dnepr"
    }
}

Your models must align with the data structure, so they should look something like this:

interface Hall {
  id: number;
  name: string;
  placeqty: number;
  cityid: City;
}

interface City {
  id: number;
  name: string;
}

When dealing with nested objects, you can use the safe navigation operator to handle potential null or undefined values. To access the city name, simply refer to that nested property like this:

<p>{{ hall.cityid?.name }}</p>

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

Automated Integration with Visual Studio Team Services: Empowering ASP.NET Core and Angular 4 Collaboration

I am currently working on an ASP.NET Core web app using Visual Studio 2017, and I am developing an Angular 4 front-end project in Visual Studio Code. The goal is for the Angular 4 project to be integrated with the Core web app, and I need to set up continu ...

What are the best practices for utilizing *ngIf?

In my Angular project, I am facing a challenge with using *ngIf. My app.component.html file handles both the login page and the dashboard. I want to hide the dashboard until the user logs in. To achieve this, I decided to use *ngIf. Here is how I implement ...

Embedding a table row within an anchor element in Angular 4

Currently, I am facing an issue with a table that contains [routerLink] on each <tr>. This setup is preventing the "open link in a new tab" option from appearing when I right-click because there is no <a> tag. I attempted to enclose the table r ...

Encountering issues with Angular 12 optimized build, the error messages are sparse and offer little

While my project compiles without any issues in development mode with the build optimizer turned off, I encounter an error during production build: ✔ Browser application bundle generation complete. ✔ ES5 bundle generation complete. ✔ Copying assets c ...

Ways to transfer specific properties from one object to another in TypeScript

I'm currently working on a function that selectively copies key-value pairs from one object to another in order to remove certain properties. The code snippet for this function is shown below: sanitizeData: function (sourceObject: object, ...allowedKe ...

Imitate a required component in a service

I am currently facing an issue with mocking a dependency in a service. I am not sure what is causing the problem. It's not the most ideal class to test, but I am mainly focused on code coverage. Below is the code for the service: @Injectable() export ...

Utilizing Angular Material's <mat-selection-list> and <mat-list-option> components seamlessly between different sections of a template

How can a <mat-list-option> declared in component sub subscribe to a <mat-selection-list> outside of component sub (for example, in component app)? (Unfortunately, I couldn't get Stackblitz to work due to my corporate's proxy restric ...

Error: Jest + Typescript does not recognize the "describe" function

When setting up Jest with ts-jest, I encountered the error "ReferenceError: describe is not defined" during runtime. Check out this minimal example for more information: https://github.com/PFight/jest-ts-describe-not-defined-problem I'm not sure what ...

I encountered a TS error warning about a possible null value, despite already confirming that the value

In line 5 of the script, TypeScript raises an issue regarding the possibility of gameInstanceContext.gameInstance being null. Interestingly, this concern is not present in line 3. Given that I have verified its existence on line 1, it is perplexing as to w ...

Oops! We encountered an error: Uncaught (in promise): [object Object]. Angular 5 version is

Trying to implement an upload button using Angular 5, I have the following code in my .ts file: handleFiles(e) { this.file = e.srcElement.files[0]; if (this.file.size > 2097152) { let snackBarRef = this.snackBar.open('Images must ...

Creating a single page application in Angular2+ using JSON data

I am looking to create an Angular JS application using the provided JSON structure: { name: 'App Name', pages: [ { name: 'Home', url: '/', layout: { type:'HTMLElement' tag:'div ...

Am I effectively implementing async await in TypeScript?

I'm not quite sure if I'm using the async/await functionality correctly in my TypeScript and Protractor code. Looking at the code snippet below, the spec uses await to call the page object, which itself is an async/await function. The page object ...

Is there a way to check for keys in a TypeScript object that I am not familiar with?

I have a good understanding of the unknown type in TypeScript. I am dealing with untrusted input that is typed as unknown, and my goal is to verify if it contains a truthy value under the key input.things.0. function checkGreatness(input: unknown) { retu ...

Enable scrolling exclusively for the content within a tab, without affecting the tab label in Clarity Tabs

I have a tab with lengthy content in my project (check out the StackBlitz reference here). This causes the appearance of a scroll. The corresponding code snippet is provided below: <div class="content-container"> <div class=&qu ...

Angular 16 routing not loading content

I configured the routes in Angular v16 and encountered a blank page issue with the login and register functionality. I suspect it has to do with routing, but after checking multiple times, I couldn't pinpoint the exact problem. Below are snippets of t ...

Issues with Angular Reactive Forms Validation behaving strangely

Working on the login feature for my products-page using Angular 7 has presented some unexpected behavior. I want to show specific validation messages for different errors, such as displaying " must be a valid email " if the input is not a valid email addre ...

encountering difficulties resolving dependency tree when attempting to generate a new Angular project

Today, I attempted to start a new Angular project using the command ng new <projectname>, but encountered the following error: npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: [email protected] npm ERR! Foun ...

Tips for displaying a modal popup in Angular with content from a separate page

I want to display a modal popup on a different page that has its body content in the app.component.html file. App.Component.html: <ng-template #template> <div class="modal-header"> <h4 class="modal-title pull-left">Modal ...

Executing Karma tests in IntelliJ with Angular 6

After upgrading my angular application from version 5.2 to version 6, everything seems to be working smoothly. However, I encountered an error while trying to run a test from IntelliJ: Error: The '@angular-devkit/build-angular/plugins/karma' ka ...

Access the elements within arrays without using the square brackets

I am trying to access data from a list, but I am having trouble using square brackets []. The getTalonPaie function calls the get method from the HttpClient service and returns an observable with multiple values. However, when I try to store these values i ...