Diego Unanue Diego Unanue - 1 month ago 9
TypeScript Question

Instantiate sub object (object inside object) Angular 2

I've got a model "Profesional" that has a property that is another model "Address":

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

export interface Profesional {
id?: number;

name?: string;

address?: Address;

and the other model:

'use strict';

export interface Adress{

id?: number;

name?: string;

The issue I'm having is in the component that uses an instance from Profesionals:

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

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

When I get from a dada base an instance of profesional, saved in a variable called profesional, the property name is set with the value from the object. But the adress gives me an error:

EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in ./CreateProfetional class CreateProfetional - inline template:48:59 ORIGINAL EXCEPTION: TypeError: Cannot read property 'id' of undefined
The ts just have the method to get a profesional instance:

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

ngOnInit() {

onGet = (id: number) => {
.subscribe(res => {
this.profesional = res


How can I instantiate this property "profesional.adress" that is an object? It is posible, or I must create a simple variable and then assign the property value to it? What it the correct way to do this?

This is the json:



Wherever you make a Professional, you must include an instantiation of Address. So:

profesional: Profesional = { address: {} };

Note that your typing of address is also wrong - it should be the interface type, not a string. Given the way you intend to use it, you may want to remove the question mark from its definition too. (OR, instead of all this, you can enclose that input with:

<div *ngIf="professional.address">

...and instantiate the address somewhere else.)