Passing data between Angular Components
Easy Way
First, let’s see the easy way of passing data between components. With this method, you can completely disregard the inheritance and other characteristics of the components in concern.
For this, you need to import and implement AfterViewInit in the component, or it will not work. Add this to the top of the Component you will use localStorage
to get values in:
import { AfterViewChecked } from '@angular/core';
Then, use:
export class HomeComponent implements AfterViewChecked {
ngAfterViewChecked(): void {
name = localStorage.getItem('keyname');
//whatever you want to do.
}
}
- To insert a value into
localStorage
:
localStorage.setItem('keyname',/*value you want to pass*/);
- To get a value from
localStorage
:
localStorage.getItem('keyname');
- To delete a value from
localStorage
:
localStorage.deleteItem('keyname');
Passing variables to Child component
Add the following in the child component:
@Input() *var name*: *data type*;
For this, you also need to import Input
from @angular/core
.
Assign attribute to child component in the html of parent :
[*var name in child*]="var name in parent"
Passing variables to Parent component
- On Event:
Register the EventEmitter
in your child component as the @Output
:
@Output() onDatePicked: EventEmitter<any> = new EventEmitter<any>();
Emit value on click:
public pickDate(date: any): void {
this.onDatePicked.emit(date);
}
Listen for the events in your parent component’s template:
<div>
<calendar (onDatePicked)="doSomething($event)"></calendar>
</div>
and in the parent component:
public doSomething(date: any):void {
console.log('Picked date: ', date);
}
- On Variable Change:
Import the following and your Child Component, in the Parent Component:
import { AfterViewChecked, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';
Add in the export class:
@ViewChild(ChildComponent) private childvar: ChildComponent;
Add implements AfterViewInit, and the function AfterViewInit:
export class ParentComponent implements AfterViewChecked{}
export class ParentComponent implements AfterViewChecked{
ngAfterViewChecked() {
// Whatever you want to do with the child component variable.
}
}