During development, we normally face situations where we need to pass the value from one component to another. Angular has provided various ways to pass such values.
Here, we are considering a scenario where we call one component inside another component, hence I have named them child and parent component.
So let's start developing the component.
- Create a component and name it as hero-child component.
use command - ng g c hero-child
- Copy the following code and paste in your hero-child.component.ts.
- import {
- Component,
- OnInit,
- Input
- } from '@angular/core';
- @Component({
- selector: 'app-hero-child',
- template: `<p>{{masterName}}</p>`,
- styleUrls: ['./hero-child.component.css']
- })
- exportclassHeroChildComponent {
- @Input('childValue') masterName: string;
- constructor() {}
- }
- Here, we have defined @Input and imported it from @angular/core. Inside inputdirective we have defined one property, 'childValue,' whose value will be set by the parent component or the component which will use hero-child component as a child component.
- We have also defined 'masterName' which is used to access the value set to 'childValue' via @Input.
- Create another component and name it as hero-parent component. Just use the command -
ng g c hero-parent- import {
- Component,
- OnInit
- } from '@angular/core';
- @Component({
- selector: 'app-hero-parent',
- template: `
- <h2>{{masters}}</h2>
- <app-hero-child [childValue]="masters">
- </app-hero-child>
- `,
- styleUrls: ['./hero-parent.component.css']
- })
- exportclassHeroParentComponent {
- masters = 'Master'
- }
- Here, we have invoked hero-child using its selector inside the template of hero-parent.
- We have also created a property named 'masters' and bound it to child component property [childValue] which we have defined inside @Input tag in child component.
- We have also bound the master's value in template <h2> tag using interpolation.
- Now, if you run the application and browse the hero-parent component, you will see master value rendered two times on the browser -- one inside <h2> tag and one via child component childValue property.