Wednesday, November 13, 2019

How to pass data from one component to another in angular

In this blog, I am going to explain to you about component communication in angular 2,4,6.

When the parent component wants to communicate child subcomponent or vice-versa so service is a good option. 

@Input
Angular provides us @Input decorator by using that we can pass data from parent component to child component. Let's see an example

child.component.ts

import { Component, Input } from '@angular/core';


@Component({
  selector: 'app-child',
  templateUrl: './childcomponent.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  @Input() name: string;
}

---------------------------------------------------------------------------------------------
In the above code first, we imported an Input decorator from 
the @angular/core package and added it in front of name property so that it can available to pass data from the parent component.

child.component.html
---------------------------------------------------------------------------------------------
<div>
   <h1>{{name}}</h1>
</div>

---------------------------------------------------------------------------------------------

Passing data from a parent component
It's time to pass data from the parent component.

app.component.html
---------------------------------------------------------------------------------------------
<div>
   <h1>Welcome to angular world</h1>
   <app-child name="Arjun"></app-child>
</div>
---------------------------------------------------------------------------------------------
In the above code, we are passing data to a child component by using a property name = "Arjun".

Passing dynamic values

We can also pass dynamic values to a child component by wrapping the property with [ ] square brackets.

app.component.ts
--------------------------------------------------------------------------------------------
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  myname = 'Arjun';
}
----------------------------------------------------------------------------------------------
app.component.html
------------------------------------------------------------------------


<div>
   <h1>Welcome to angular world</h1>
   <app-child [name]="myname"></app-child>
</div>
---------------------------------------------------------------
Output are as below :-

Welcome to angular world Arjun



Thank you ..

Arjun Walmiki


No comments:

Post a Comment