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

A Unique Identifier in Kotlin

In my typescript class, I have a member that accepts any as the name: interface ControlTagType { type?: String | null; [name: string]: any } class ControlTag { tagSource: String | null = null; tag: ControlTagType | null = null; } expor ...

Angular2 routing does not trigger the Component constructor and Router life-cycle hooks when the router.parent.navigate method is called from a child component

I am currently working on an application that includes child routes. The parent component (App component) consists of 2 routes: @RouteConfig([ { path: '/overview', name: 'Overview', component: OverviewComponent, useAsDefault:true }, { ...

Angular2 and Typescript paired with Visual Studio 2013

Currently, I am utilizing the angular2 QUICKSTART and encountering an issue where Visual Studio fails to recognize Angular2 with typescript import Modules. However, everything else seems to be functioning correctly: https://i.stack.imgur.com/0s46Y.jpg Th ...

How can we fetch data from the server in Vue 2.0 before the component is actually mounted?

Can anyone help me with this question noted in the title? How can I prevent a component from mounting in <router-view> until it receives data from the server, or how can I fetch the data before the component is mounted in <router-view>? Here a ...

Having trouble injecting ActivatedRouteSnapshot into the component

Struggling to inject ActivatedRouteSnapshot into a component, encountering errors when trying to access query params. Here is the error stack trace: "Error: Can't resolve all parameters for ActivatedRouteSnapshot: (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?). a ...

React TypeScript: The properties of 'X' are not compatible. 'Y' cannot be assigned to 'Z' type

I am currently working on a React-TypeScript application, specifically creating a component for inputting credit card numbers. My goal is to have the FontAwesome icon inside the input update to reflect the brand image as the user enters their credit card n ...

Utilize Firebase to perform a case-insensitive query

Our Angular/Ionic app requires users to provide their email during registration, which is then saved in the User collection. We also validate if the email is already in use with a query like this: firestore .collection("User") .where("email", "==", ...

How to access type properties in typescript without using the "this" keyword

Below is a snippet of code that I am working with: class Player implements OthelloPlayer { depth; constructor(depth: number) { this.depth = depth; } getMove(state: OthelloState) { return this.MinimaxDecision(stat ...

After calling sequelize.addModels, a Typescript simple application abruptly halts without providing any error messages

My experience with Typescript is relatively new, and I am completely unfamiliar with Sequelize. Currently, I have only made changes to the postgres config in the .config/config file to add the dev db configuration: export const config = { "dev" ...

Updating dynamically rendered component content with ngComponentOutlet in Angular 11: A comprehensive guide

I am working on an Angular 11 app that includes a menu generated from an array of objects with specific properties: { icon: CUSTOMER_ORDER_PROPERTIES.icon, iconColor: CUSTOMER_ORDER_PROPERTIES.color, label: 'Search Customer Order', routeB ...

What is the best way to ensure observables in a template (using async pipe) are fully subscribed to before executing any initialization code?

I am facing an issue with my HTTP service that returns information based on a given item ID. The data is fetched using a Subject, which receives the initial data in the ngOnInit method. To display the returned data in the HTML, I utilize the async pipe. ...

How to easily deactivate an input field within a MatFormField in Angular

I've come across similar questions on this topic, but none of the solutions seem to work for me as they rely on either AngularJS or JQuery. Within Angular 5, my goal is to disable the <input> within a <mat-form-field>: test.component.h ...

Utilizing Angular 14 and Typescript to fetch JSON data through the URL property in an HTML

Is there a way to specify a local path to a JSON file in HTML, similar to how the src attribute works for an HTML img tag? Imagine something like this: <my-component data-source="localPath"> Here, localPath would point to a local JSON fil ...

The font awesome symbol is not showing up in the nz-th element

I've encountered an issue with the code snippet below: <th [ngSwitch]="sortIcon" nz-th class="centered" (click)="toggleSortOrder()" nzSort="Stopped">Sort <i *ngSwitchCase="sortEnum.NoSort" class="fa fa-lg fa-fw fa-sort"></i> ...

Delay the execution until all promises inside the for loop are resolved in Angular 7 using Typescript

I am currently working on a project using Angular 7. I have a function that contains a promise which saves the result in an array as shown below: appendImage(item){ this.imageCompress.compressFile(item, 50, 50).then( result => { this.compressedI ...

Errors encountered while starting Angular due to issues in package.json configuration

Summary: Encountered an error while using 'Angular' for the first time, indicating tsc was not found in the package.json file. Details: As a beginner with Angular, I followed an example from a book and attempted to start it with np ...

Doughnut Chart with Color Gradients in ng2-charts

Currently, I am exploring the world of Chart.js and ng2-Charts within Angular. Specifically, I am experimenting with Doughnut Charts and have a desire to create a Multi Level Chart. However, I am facing an issue where I am unable to customize the colors fo ...

Combining Angular, Node.js, and Spring Boot Java REST API to enable Angular Universal functionality

I am seeking guidance on integrating Angular with NodeJS and Spring Boot for my application. Currently, I have built a system that utilizes Angular for the frontend and Java/Spring Boot for the backend REST API. However, I have come across challenges with ...

`Angular Image Upload: A Comprehensive Guide`

I'm currently facing a challenge while attempting to upload an image using Angular to a Google storage bucket. Interestingly, everything works perfectly with Postman, but I've hit a roadblock with Angular Typescript. Does anyone have any suggesti ...

What is the best way to manage optional peer dependency types while releasing a TypeScript package?

I'm trying to figure out the best way to handle optional peer dependencies when publishing a TypeScript package on npm. My package provides a function that can accept input from either one of two peer dependencies. How should I define these optional p ...