Angular 2: passing object with nested object to child component

I have nested object

data: {
  nestedData: {
    title: 'string'
  }
};

I pass this data to child component via property

<child-component [data]="data"></child-component>

Child component code:

import {Component, Input} from 'angular2/core';

@Component({
  selector: 'cp-header',
  template: '<div>{{ data.nestedData.nestedData }}</div>',
  styleUrls: ['app/header/header.component.css']
})
export class ChildComponent {
  @Input() data;
}

Then when I try to access object property in template I got error;

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

Try using elvis operator in your HTML: data?.nestedData?.title.

You should also change @Input data to @Input() data.

Jason
Guest

You can’t access inputs in the constructor. They are set just before ngOnInit is called:

export class ChildComponent {
  @Input data;

  constructor() {
    console.log(this.data); // here it prints `null`
  }

  ngOnInit() {
    console.log(this.data); // here it prints the actual value
  }
}