Create a nested object within an object in Angular 2

I am currently working with a model named "Professional" which includes a property that is another model called "Address":

   'use strict';
import * as Address from './models/address';

export interface Professional {
    id?: number;

    name?: string;

    address?: Address;
}

Here is the definition of the Address model:

    'use strict';

export interface Address{

    id?: number;

    name?: string;
}

The challenge I'm facing is in the component that utilizes an instance of Professionals:

    <input type="text" [(ngModel)]="professional.name">

    <input [(ngModel)]="professional.address.id" class="form-control">

When retrieving an instance of a professional from a database and saving it in a variable called "professional", the property "name" is successfully set to the object's value. However, I encounter an error while accessing the "address" property:

EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in ./CreateProfessional class CreateProfessional - inline template:48:59 ORIGINAL EXCEPTION: TypeError: Cannot read property 'id' of undefined The TypeScript code contains the method to retrieve a professional instance:

import { Component, OnInit  } from '@angular/core';
import { DefaultApi } from '../../../api/api/DefaultApi';
import {Professional} from '../../../api/model/Professional';
import {Address} from '../../../api/model/Address';
declare var $: any;
@Component({
  selector: 'professionals',
  styles: [require('./professionals.component.css').toString()],
  template: require('./professionals.component.html'),
  providers: [DefaultApi]
})
export class CreateEditProfessionalsComponent {
  professional: Professional = {};

  ngOnInit() {
        this.onGet(1);  
  };

  onGet = (id: number) => {
    this._apiDentos.findProfessionalById(id.toString())
      .subscribe(res => {
        this.professional = res
      },
      console.error);
  };

}

Is there a way to properly instantiate the "professional.address" property since it is an object? Should I create a separate variable and then assign the property value to it? What is the correct approach?

This is how the JSON data looks like:

{  
   "id":1,
   "name":"1",
   "address":{  
      "id":1,
      "name":"fsda"
   }
}

Answer №1

Firstly, it is important to mention that within your Expert interface, you must change the address type from string to Address. It is essential to initialize at least the sub-objects to prevent exceptions:

expert: Expert = <Expert>{ 'location' : {} };

An even better approach would be to initialize all attributes, although this decision should be based on the specific domain.

Answer №2

When creating a Professional, remember to include an instantiation of Address. For example:

professional: Professional = { address: {} };

It's important to note that your declaration of the address is incorrect - it should be the interface type, not a string. You may also want to consider removing the question mark from its definition based on how you plan to use it. Alternatively, you can surround the input with:

<div *ngIf="professional.address">

...and initialize the address elsewhere.

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

Set up a jquery code that ensures a loading effect will only be displayed one time

After clicking on a specific icon, I dynamically add a loading message to the DOM. The issue arises when the user clicks twice, resulting in two instances of the loading message appearing simultaneously. How can I ensure that only one "loading..." message ...

Utilize the ng-controller directive with unique aliases across various sections of HTML code

I'm facing an issue with my ng-controllers when multiple controllers are used on the same page. For instance, I have one controller in the page header, another in a different section of the same page, and one in the content of the page. However, all o ...

Another class is overriding the border of the text-box

I'm facing a challenge in customizing the material ui css. Specifically, I want to set the border color of a textbox to red. The issue arises when the bottom border gets overwritten. Upon investigation, I discovered that the culprit is the class MuiIn ...

Choose the appropriate sprite based on the calculated result

I have a PNG file with 30 sprites in it. After converting it into CSS using , I am facing an issue with my JavaScript code. The script generates a random number between 1 and 30, and I need to select the corresponding sprite based on this number. .sprit ...

Components not reflecting custom theme settings

I've been struggling to implement my custom theme, which consists of a simple color change, from Theme.js to the components in App.js. Despite my efforts, the components continue to display the default theme colors and I have been unable to change the ...

Utilize jQuery to locate the class that appears earlier in the DOM tree

Can someone assist me with retrieving the previous occurrence of a class within a specific portion of the Dom Tree using jQuery? If there is no previous occurrence, I would like to be informed about it. To clarify further, by "previous occurrence" I mean ...

In Firefox version 3.6, sIFR 3 is displaying text in a random arrangement along a single line

For some reason, sIFR 3 is behaving oddly in Firefox. In other browsers like IE, Chrome, and Safari, the Flash element within a 412px wide box remains consistent at that width. However, in Firefox, it initially stretches to the width of the Body element b ...

Having difficulties retrieving footer Fields using cheerio library

https://i.sstatic.net/TlsIZ.png When utilizing node and cheerio to scrape the header and footer of a table, I encountered an issue with my code. Below is the entire table HTML and my code snippet: async function getTableFooter(html) { const $ = cheerio ...

What is the best way to ensure that all function parameters using a shared generic tuple type have a consistent length?

Understanding that [number, number] | [number] is an extension of [number, ...number[]] is logical, but I'm curious if there's a method to enforce the length of tuples based on the initial parameter so that the second tuple must match that same l ...

Dealing with Asynchronous JavaScript code in a while loop: Tips and techniques

While attempting to retrieve information from an API using $.getJSON(), I encountered a challenge. The maximum number of results per call is limited to 50, and the API provides a nextPageToken for accessing additional pages. In the code snippet below, my i ...

Discovering mutual friends on Facebook through the Graph API

I developed an application that displays mutual friends for users. To retrieve mutual friends on my node server, I have implemented the following code: var express = require('express'), FB = require('fb'), appFB = FB.extend({appId: & ...

What is the best way to retrieve widget options when inside an event?

Creating a custom jQuery widget: jQuery.widget("ui.test",{ _init: function(){ $(this.element).click(this.showPoint); }, showPoint: function(E){ E.stopPropagation(); alert(this.options.dir); } } Initializing the cu ...

Pictures are not aligning correctly within a div element on Safari

When viewing the images in the images div on Chrome, Firefox, and IE, they appear to be vertically aligned and centered properly. However, there seems to be an issue with Safari as the pictures are being pushed below or out of the images div, causing them ...

Switching a button's appearance by clicking on a different row

This form contains a toggle edit feature. <% while(resultset.next()){ %> <form method='POST' class="formfield" action='EditCompany'> <tbody> <tr align='center' class='form'> <td><% ...

What is the location for adjusting the angular strictness flags that determine the level of strictness for strictTemplates?

Currently in the process of transitioning our application to strictTemplates, we are encountering a multitude of errors, some more significant than others. As a result, I decided to adjust the strictness of the angular type checker and came across these s ...

Conceal the Jquery Class if there are no classes currently visible

There is a section of text labeled (16 Courses) below that I am trying to hide using JQuery, but so far, all my attempts have failed. Can anyone offer any guidance on how to successfully hide only this particular text? <div id="programAttributes"> ...

Debugging the Force-Directed D3 Graph

I stumbled upon a fantastic article that provided a detailed guide on creating a beautiful D3 force layout graph. However, I'm facing some difficulties with the JSON source: The "links" attribute in the author's JSON doesn't seem clear to m ...

Using Vue to input an array

I'm struggling with how to handle this issue. The task involves taking input which should be a URL, and the user should be able to enter multiple URLs. For instance: <input type="text" v-model="fields.urls" class=&quo ...

Using the JSON method within child classes

I am working with a base class called TransportationVehicle: class TransportationVehicle { String vehicleName; TransportationVehicle(this.vehicleName); Map<String, dynamic> convertToJson() { final Map<String, dynamic> js ...

Leveraging the .reduce method to perform specific calculations and generate an object containing the results of an array

After successfully achieving the desired results, here is the data manipulation I have done: const days = [ { date: '2016-12-13T00:00:00.000Z', stats: [ { name: 'Soft Drinks', sold: 34, }, { name: 'Snacks&apo ...