Blog>
Snippets

Dealing with Complex Objects as @Input Data

Provide an example of a child component that receives and displays data from a complex object passed as an @Input.
import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-child-component',
  template: `
    <div *ngIf="complexData">
      <h2>{{ complexData.title }}</h2>
      <p>{{ complexData.description }}</p>
      <ul>
        <li *ngFor="let item of complexData.items">{{ item }}</li>
      </ul>
    </div>
  `
})
export class ChildComponent implements OnInit {
  @Input() complexData: any;

  ngOnInit(): void {
    // Perform initialization or deep data validation/manipulation here if needed
    console.log('Received complexData: ', this.complexData);
  }
}
This is an Angular child component that uses an @Input decorator to receive a complex object from its parent component. The template uses Angular's structural directives *ngIf and *ngFor to conditionally display the complex data and iterate over its `items` array. The ngOnInit lifecycle hook is used for additional initialization or validation of the complex data.