Reputation: 458
How do i get to pass, data around or call a function from one component to another in angular application 4, 5 or 6. let's say i have my parent component with two or more component.
Upvotes: 0
Views: 554
Reputation: 147
You create a service for that. The data in a service is shared among all the components. You can move all your data and functions to a specific service and call that service. For example:
constructor(private myservice: MyService){};
.ts
this.myservice.myfunc();
this.myservice.mydata;
.html
{{myservice.mydata}}
Upvotes: 1
Reputation: 458
the first thing here is to create a service component like this:
import { Injectable } from '@angular/core';
import { BehaviorSubject, Subject, Observable } from 'rxjs';
@Injectable()
export class DataService {
constructor() { }
private data = new BehaviorSubject<string>("Home");
//this is what your components subsribes to
currentData() : Observable<string> {
return this.data.asObservable();
}
//this function allows you to change the value to be accessed by other components
changeData(message: string) {
this.data.next(message);
}
}
this next step is setting your parent component to subscribe to the data service, as shown below.
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
//component member variable to be changed on value change detection
message = "";
//here you'll inject in your component constructor the service declaration
constructor(private data: DataService) {
}
ngOnInit(){
this.data.currentData().subscribe((message:string) => {
//here i log changes detected on the console
console.log("i have changed");
//you can perform any call or action here e.g
//update a variable
this.message = message;
//or call a function
canCall();
});
}
canCall(){
console.log("i am called.");
}
}
then after this every other components, can pass/change value and your parent component will pick up these changes and perform your logic.
import { Component, OnInit } from '@angular/core';
import { DataService } from './../data.service';
@Component({
selector: 'app-productreview',
templateUrl: './productreview.component.html',
styleUrls: ['./productreview.component.css']
})
export class ProductreviewComponent implements OnInit {
//here we inject the data service just like before
constructor(private data: DataService) { }
//optional
ngOnInit(){
this.data.currentData().subscribe((message:string) => this.currentAction = message);
}
//this where we change the data
changeData(option: string = "New Data"){
this.data.changeData(option);
}
}
Upvotes: 2