While there are several ways to make properties available throughout your Angular app, I found this 3-step process pretty easy to follow and remember.
For the sake of simplicity, we call the parent component Parent and the child component Child. If you prefer a more practical approach, check out this practical example to get a better understanding.
Here are the three steps to pass a property to a child component:
1. Prepare Child.ts for external Input
Prepare the child component class (Child.ts) to receive external inputs.
- External refers to data that is not available inside the component itself (In this case, Child).
- Input refers to the property that the parent component (Parent) passes to the child component.
// Child.ts
export class Child implements OnInit {
@Input() expectedProp: { title: string };
constructor() {}
ngOnInit(): void {}
}
The @Input()
decorator expects a property that we named expectedProp. You can name this property as you wish but remember to be consistent in the next steps.
This custom property is of type object with a key named title of type string.
2. Bind Property in Parent.html
First of all, we have some data in our parent component class (Parent.ts)
// Parent.ts
export class AppComponent {
book = { title: 'Principles' }
}
We want to pass book to Child.
To do so, we do two things in Parent.html:
- We use the selector
<child></child>
to use the child component. - We need to bind the data coming from the parent component class (Parent.ts) to the custom property, expectedProp, that we declared in Child.ts.
Quick recap:
- Data in Parent.ts: book
- Custom property in Child.ts: expectedProp
- Property binding syntax: [property]="data"
The binding happens in Parent.html which becomes the point of contact between Parent.ts and Child.ts
// Parent.html
<ul>
<child
[expectedProp] = "book"
>
</child>
</ul>
3. Use Property in Child.html
The custom property is now available in Child and it can be used in Child.html.
As a result, we can use interpolation binding syntax (double curly braces) to presents the component's property value inside the template.
// Child.html
<li>
{{expectedProp.title}}
</li>
Conclusions
If this seems too abstract, check out this practical example.
Otherwise, remember the three steps:
- Prepare Child.ts for external Input
- Bind Property in Parent.html
- Use Property in Child.html
Top comments (2)
Thanks for your serie!
How about HTML template, how can we pass from child to parent?