Show the interface value for an array type

I have created a component to display API data. The structure of the component is as follows:

HTML:

<div  *ngFor="let  customer of customers">
   <p>Name: {{customer?.name}}</p
   <p>Phone: {{customer?.phoneNumbers}}</p
</div>  

TS

import { Component,  Input } from '@angular/core';
import {  Customer } from '../models';

 @Component({
   selector: 'yn-contact',
    templateUrl: './contact.component.html',
    styleUrls: ['./contact.component.css'],
  })

 export class ContactComponent  {
     @Input()
     public customers: Customer ;
   }

An interface Customer has been declared in a file called models.ts. Here is how it looks:

models.ts file

  export interface Customer {
     name: string;
     phoneNumbers: PhoneNumber[];
  }

  export interface PhoneNumber{
    type: string;
    displayName: string;
    number: string;
  }

While I am able to display the name field in the HTML, there seems to be an issue with displaying the phoneNumbers. It currently shows as a link instead of the actual phone numbers:

https://i.stack.imgur.com/tMxi7.png

JSON:

  { 
    "salutation": "Dr",
    "jobTitle": "Nurse Practicioner",
    "name": "Adaline Danat",
    "birthDate": "1964-06-04T06:31:10Z",
    "gender": "Female",


   "phoneNumbers": [
       {
        "type": "Unknown",
        "displayName": "Mobile",
        "number": "+62 342 886 8201"
      },
      {
        "type": "Other",
        "displayName": "Home",
        "number": "+86 707 128 1882"
      },
      {
        "type": "Business",
        "displayName": "Home",
        "number": "+63 704 441 1937"
      },
    ],

   }

Answer №1

 <div *ngFor="let client of clients">
     <p>Name: {{client?.name}}</p>
       <ng-container *ngFor="let number of client?.phoneNumbers">
         <p>Phone Number: {{number.phoneNumber}}</p>
        </ng-container>
   </div>  

To display other information, you can simply use {{number.displayName}} within the inner loop.

Answer №2

To access the phone number, you will need to use the key (number) from the phone object. Here's an example:

{{customer?.phone[0]?.number}}

Additionally, for debugging purposes in the view side, you can utilize the json pipe in HTML like so:

{{customer?.phone | json}}

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 an event listener in vanilla JavaScript with TypeScript

Can anyone help me figure out how to correctly type my event listener in TypeScript + Vanilla JS so that it has access to target.value? I tried using MouseEvent and HTMLButtonElement, but I haven't been successful. const Database = { createDataKeys ...

The value of an Angular rxjs BehaviorSubject can be updated using the value property directly, without calling

While testing my code, I stumbled upon unexpected mutation. Perhaps I am doing something wrong. User constructor( public id: number, public education: Education[] ){} UserStateService private user = a new BehaviorSubject<User>(null); setUser(us ...

Accessing and manipulating a intricate JSON structure within an Ionic 3 framework to seamlessly connect it to the user

I'm currently developing an app using Ionic 3. Within my project, I have a JSON object structured like this: { "player": { "username": "thelegend", "platform": "xbox", "stats": { "normal": { "shots ...

Setting the selected value of a static select menu in Angular 2 form

I'm having an issue with my Angular 2 form that includes a static select menu. <select formControlName="type" name="type"> <option value="reference">Referentie</option> <option value="name">Aanhef</option> &l ...

Ways to retrieve the component name from a service in Angular without relying on private APIs such as view container refs

How can I access the component name inside a service that is calling a method within the service? I have tried using console.log(this.vcr['_view'].component) and console.log(this.vcr['_view'].component.constructor.name), but they do not ...

The input of 'Response' does not match the expected type of 'string'

I am currently working on a project that involves retrieving books from the Google Book API using Angular 4. Although I am still learning Angular, I am facing challenges in understanding how to read the JSON response. During my research online, I came acr ...

Incorporate a CSS framework into the Angular vendor bundle

My current situation : The website is built with Angular 4 Started using Angular Starter Kit Utilizing Semantic UI as the CSS framework The challenge I'm facing : Integration of Semantic UI into webpack is not having any impact. Steps I've ...

Is it possible to retrieve data from a promise using the `use` hook within a context?

Scenario In my application, I have a component called UserContext which handles the authentication process. This is how the code for UserProvider looks: const UserProvider = ({ children }: { children: React.ReactNode }) => { const [user, setUser] = ...

Stream of information that triggers a specific action based on a specified condition

I'm dealing with an observable stream where I need to make two calls after retrieving the initial object using two id's found within the object. One of these id's, siteId, is optional and may or may not be present. If it is present, I need t ...

What is the reasoning behind TypeScript's decision to permit implicit downcasting in method parameters?

Consider the following example: interface Vehicle{ mass:number } interface InspectorClass{ inspect(v:Vehicle):void } class Car implements Vehicle{ mass = 2000 wheels = 4 } class Boat implements Vehicle{ mass = 3000 sails = 2 } ...

What is the best way to create and manage multiple collapsible Material-UI nested lists populated from an array with individual state in React

In my SideMenu, I want each list item to be able to expand and collapse independently to show nested items. However, I am facing the issue of all list items expanding and collapsing at the same time. Here is what I've attempted: const authNavigation ...

How can I extract data from the 'ngx-quill' editor when integrating it with a FormBuilder in Angular?

After implementing the 'ngx-quill' editor package in my Angular 15 project, I encountered an issue where the value of the content form control was returning 'null' upon form submission using FormBuilder. Despite entering text such as he ...

Ways to conceal and reveal image and text elements based on array loop output

I am currently working on setting up a questionnaire. The questions and answer options are being pulled from a database using an API. Some of the options include images, with the image link stored in the database. I am trying to find a solution where text ...

TS2307: encountered an issue finding the module (all modules) after relocating directories

My decision to reorganize modules led me to start moving folders in order to achieve better organization: This caused a change in app.module.ts: app.module.ts with important part of debug.log However, when attempting to use npm install or ng serve, I en ...

Troubleshooting a child process created by electron in Visual Studio Code

I am currently in the process of developing an electron application using typescript and webpack. I have encountered a specific debugging issue with vscode that I would like some assistance with: Context: The main process initiates a child process by call ...

Utilizing Angular and Typescript for Enhanced Modal Functionality: Implementing Bootstrap Modals in Various Components

When working in Angular, I have a component called Modal. I need to open the same Modal Component from two different places. The catch is, I want the button text in the Banner image to say "Get Started Now". Check out the Image linked below for reference. ...

Issue: Angular 2 is missing the runtime compiler component

In my Angular2 project, I utilized the compiler service to create a dynamic module and render it at runtime in the app. However, an issue arises when I run the command ng build --prod. The process completes without any errors, but upon hosting it on heroku ...

What is the best way to iterate through an array within a class in Angular 2?

I am trying to iterate over an array named data, within another array containing 'champions'. Can anyone provide the correct syntax for this? I can successfully loop through all the champions within my IChampion interface, but I'm having tro ...

Adding an object to an array in Angular 7: A step-by-step guide

Why am I facing issues while pushing an object into an array? This is how I am attempting to do it: this.passData = this.tribeForm.value; var id = {"tribe_id": 1} this.passData.push(id) Shown below is the value in the tribeForm https://i.sstati ...

gather and handle data from the shared interface between different parts

I have two different paths. One is for products and the other is for products-cart. I want to use a shared ts file for both to store the product and cart information in an array. However, I am encountering an issue. I am unable to make any changes or trans ...