Angular @Input decorator
Hai Welcome in lets make this more interesting….lets learn about @Input decorator in Angular..
Sharing data between child and parent directives and components using @Input decorator;
- @Input decorator makes the way to communicate between the child and the parent component
# sharing data ;
- Here the property is received from the parent component here to use @Input() first we must configure the child and the parent
# configuring the child;
To configure first we must import the @Input() decorator . and decorator the property with input
for eg:
In this example i have created the server-element.component here in this type Script file decorate the property with @Input decorator
import { Component, Input, OnInit } from ‘@angular/core’;
export class ServerElementComponent implements OnInit {
@Input() element = ‘’; /* decorate the property with @Input decorator */
}
here the decorator property which has the type string , however @Input decorator can have the property of any type such as number, boolean, string or object .the value comes from the parent component
for eg;
in the server-element.component.html file
<p>i am : {{element}}</p>
# configuring the parent component;
Here we need to bind the property in the parent component template. the parent component template which used here is app.component.html
Use the child’s selector, here <app-server-element>, as a directive within the parent component template.
Use property binding to bind the “element” property in the child to the current element property of the parent.
for eg;
in the app.component.html
<app-server-element [element]=”currentelement”></app-server-element>
Designate a value for currentelement in the app.component.ts file
for eg;
in the app.component.ts
export class AppComponent {
currentelement = ‘good’;
}
With @Input(), Angular passes the value for currentelement to the child so that element renders as good
The target in the square brackets, [] , is the property you decorate with @Input in the child component. The binding source, the part to the right of the equal sign, is the data that the parent component passes to the nested component.