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

Error: Type '() => () => Promise<void>' is not compatible with type 'EffectCallback'

Here is the code that I'm currently working with: useEffect(() => { document.querySelector('body').style['background-color'] = 'rgba(173, 232, 244,0.2)'; window.$crisp.push(['do', 'ch ...

What could be the rationale behind the optional chaining operator not being fully compatible with a union of classes in TypeScript?

Imagine I have a combination of classes: type X = ClassA | ClassB | ClassC; Both ClassA and ClassC have a shared method called methodY. Why is it that I can't simply use the optional chaining operator to call for methodY? class ClassA { methodY ...

Guide on utilizing a declaration within a third-party module

I have encountered an issue while using the fingerprintjs2 library, as the declaration provided in DefinitelyTyped seems incomplete and incompatible. In order to resolve this, I decided to create my own declaration within my project. However, I am facing ...

Setting up the foundations in Angular 4

Using WebStorm 2017.1.4, I am working on creating the front end of my J2EE application. Within this project, I have two components: "about" and "contacts". In the latter component, my goal is to include all contacts from a MySQL database. However, I encoun ...

Dealing with Errors in Angular 8: Best Practices for Handling Response Errors

When an error is thrown from the WEB API, I do not receive any response and the debugger does not hit. However, in case of success, I do get a response and the debugger hits. All I want is to receive an error response and have the debugger hit every time, ...

Troubleshooting error messages in Angular related to scss ModuleBuild

I've been working on applying a theme to my Angular application, but I've run into an issue. It seems that the src/theme.scss file I created is functioning correctly on its own. However, when I try to import "~@angular/material/theming", I encoun ...

Listening for Backdrop Click in Angular NgBootstrap Modal

Whenever I open the modal, a form will appear. If the user starts filling out the form but accidentally clicks on the backdrop, the default action is for the modal to close. However, I am interested in capturing this event because I want to display a new ...

Converting Venn diagram code from JavaScript <script> tags to Angular 2: A step-by-step guide

I am struggling to incorporate a Venn diagram into my Angular 2+ project. I followed the code sample provided at - http://jsfiddle.net/johnpham92/h04sknus/ To begin, I executed the following command - npm install venn.js Then I proceeded with impl ...

I'm trying to resolve the "Uncaught TypeError: Cannot read property '0' of null" error that keeps popping up in my Mobx action within a Firebase and React application. Can anyone offer some guidance on

I've encountered some errors while working on a Mobx React application that occurs when I navigate to the /login page, despite being logged in. Here's a snippet of my code: index.tsx (Code Snippet Here) App.tsx (Code Snippet Here) Login.tsx ...

Is there a program available that can efficiently convert or translate JSON objects into TypeScript types or interfaces?

Can anyone recommend a tool that can easily convert a JSON object into a TypeScript type or interface? An example input would be something like this: I'm hoping to paste the JSON object into the tool and receive an output structure similar to: expor ...

Binding user input to a preset value in Angular with data binding

My goal is to have a predefined input form with the email provider value preset. However, when I try to submit the form without modifying it, it does not upload anything to Firebase unless I manually delete the value and re-enter it. <input class="butt ...

Typescript iterative declaration merging

My current project involves creating a redux-like library using TypeScript. Here is an example of the basic action structure: interface ActionBase { type: string; payload: any; } To customize actions for different types, I extend the base interface. ...

Include a fresh attribute in the Interface

How can I include a boolean property isPhotoSelected: boolean = false; in an API interface that I cannot modify? The current interface looks like this: export interface LibraryItem { id: string; photoURL: string; thumbnailURL: string; fi ...

After closing and reopening the app, I noticed that the ionic slider images fail to display until I navigate to the next page

//// How can I retrieve the data for (let i = 0; i < res.length; i++) { let item: any = {}; item.slide = res.item(i).slide; items.push(item); } this.productsService.setSlideList = items; setTimeout(() => { this.sliderImage = items; consol ...

`It is important to note that in Tailwind CSS, `h-8` does not supersede `h-4

I developed an Icon component that looks like this: import { IconProp, library } from "@fortawesome/fontawesome-svg-core"; import { far } from "@fortawesome/free-regular-svg-icons"; import { fas } from "@fortawesome/free-solid-svg- ...

Determining the return type of a function by analyzing its argument(s)

I'm interested in defining a method within a class that will have its type based on the argument provided in the constructor. For example: class A { private model: any; constructor(model: any) { this.model = model; } getModel( ...

Support for Chrome in Angular 8

Can someone please advise on the minimum version of Google Chrome that is supported by Angular 8? Additionally, I am looking for a way to prompt users to update their Chrome browser if it doesn't meet the required version. My Angular application seems ...

Troubleshooting an Issue with MediaStreamRecorder in TypeScript: Dealing with

I've been working on an audio recorder that utilizes the user's PC microphone, and everything seems to be functioning correctly. However, I've encountered an error when attempting to record the audio: audioHandler.ts:45 Uncaught TypeError ...

Updating the value of the chosen drop down option upon selection

I currently have a Material UI dropdown menu implemented in my project. My goal is to use the selected option from the drop down menu for future search functionality. How can I utilize onChange() to store the selected option effectively? At the moment, I ...

What is the best way to grasp the connections between the any, unknown, {} data types and their relationships with other types?

Seeking to comprehend relationships between different types, the following code is presented: type CheckIfExtends<A, B> = A extends B ? true : false; type T1 = CheckIfExtends<number, unknown>; //true type T2 = CheckIfExtends<number, {}> ...