What is Child Component | Custom Property Binding | @Input()| Angular 15+
We can pass data from component class to view template and vice versa using property binding, string interpolation and event binding.
We can also pass data from parent component to child component and vice versa. We use @lnput & @Output decorator for that.
You can use your components in other components as well instedd of parent component
Custom Property Binding
We can pass data from parent component to child component using @lnput decorator.
We also call it custom property binding because here we bind the custom properties of child component class with the property or method of parent component class.
1. First of all import Input module in child component
import { Component, Input } from '@angular/core';
2. Add Input decorator in child component, it will be used to get data from parent component
@Input() fromParentIGotvalue:number = 0;
SO HERE is example:we create parent component
products.component.html
[CHILDCOMPONENT-VARIABLE] ="PARENTCOMPONENT"
<div>
<app-filter [fromParentIGotvalue]="ihaveProducts"></app-filter>
I have {{ihaveProducts}} Products
</div>
products.component.js
export class ProductsComponent {
ihaveProducts:number = 50;
IhaveFreeProducts = 12;
}
app-filter is child component in parent, and we pass IhaveFreeProducts variable to that child component
Now access this in child component
filter.component.html
<p>filter works! and have {{freeCourses}} free courses</p>
<p>In parent I found {{freeproducts}} free courses</p>
filter.component.ts
we import Input and use decorater to access the value
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-filter',
templateUrl: './filter.component.html',
styleUrls: ['./filter.component.css']
})
export class FilterComponent {
freeCourses:number = 10;
@Input() freeproducts:number = 0;
}