Angular offers several mechanisms for sharing data across components, but a straightforward three-step pattern makes property passing from a parent to a child easy to implement and recall.

For clarity, the parent component is referred to as Parent and the child as Child. If a hands-on demonstration is more your style, you can follow this practical example for a deeper understanding.

The process to pass a property into a child component boils down to these three actions:

1. Set Up Child.ts for Incoming Data

First, the child component class (Child.ts) must be configured to accept values from outside its own scope.

  • External means data that originates outside the component itself (in this scenario, Child).
  • Input denotes the actual property that the parent component (Parent) sends down to the child.
// Child.ts

export class Child implements OnInit {
  @Input() expectedProp: { title: string };
  constructor() {}

  ngOnInit(): void {}
}

Enter fullscreen mode Exit fullscreen mode

The @Input() decorator is applied to a property named expectedProp. This name is arbitrary, but staying consistent in the subsequent steps is essential. The custom property is an object containing a string key named title.

2. Bind the Property in Parent.html

First, the parent component class (Parent.ts) holds the data we intend to share.

// Parent.ts

export class AppComponent {

  book = { title: 'Principles' }

}
Enter fullscreen mode Exit fullscreen mode

The goal is to pass the book variable down to the Child component. This is achieved with two actions in the Parent.html file:

  1. The <child></child> selector is used to render the child component.
  2. The data from the parent class (Parent.ts) is bound to the custom property, expectedProp, defined in Child.ts.

To recap:

  • Data in Parent.ts: book
  • Custom property in Child.ts: expectedProp
  • Binding syntax: [property]="data"

This binding is done in Parent.html, which acts as the bridge connecting Parent.ts and Child.ts.

// Parent.html 

<ul>
  <child 
    [expectedProp] = "book"
    >
  </child>
</ul>

Enter fullscreen mode Exit fullscreen mode

3. Consume the Property in Child.html

Once configured, the custom property is accessible within the Child component and can be used in its template (Child.html). You can use interpolation binding with double curly braces to display the value of the property within the HTML.

// Child.html

<li>
  {{expectedProp.title}} 
</li>

Enter fullscreen mode Exit fullscreen mode

Wrapping Up

If the abstract steps are unclear, refer to this practical example for guidance.

Ultimately, the key steps to remember are:

  1. Prepare Child.ts for external Input
  2. Bind Property in Parent.html
  3. Use Property in Child.html