Reputation: 619
I am new to angular and I am basically trying to pass one component to other component in the template.
I have created a new ng project via ng new new-proj
and this is my code
//contents inside app.component.html
<app-g-table [inputVariable] = "data"> //Table Component
<app-g-column [name]="'Employee'"></app-g-column> //Column Component
</app-g-table>
I need to get the data of Column Component[app-g-column] (in this example
'Employee') inside app-g-table.ts
Is there any way to achieve this?
<app-g-table [inputVariable] = "data"> //Table Component
<app-g-column [name]="'Employee'" [isVisible]="true"></app-g-column> //Column Component
<app-g-column [name]="'Age'" [isVisible]="false"></app-g-column> //Column Component
</app-g-table>
I was wondering if I can directly use components (app-g-column) inside (app-g-table) directly?
Upvotes: 2
Views: 147
Reputation: 413
I have shared the solution to your question. Check here
https://stackblitz.com/edit/angular-xuxd7a
OR
First, create a sharedService
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable()
export class SharedService {
myData: Subject<any> = new Subject<any>();
constructor() {}
setData(data) {
this.myData.next(data);
}
}
Then from where you want to set the data use this method:
export class Component1 implements OnInit {
constructor(private sharedService: SharedService) { }
ngOnInit() {
this.sharedService.setData(data);
}
}
Then in your Component2 where you want to display the data:
export class Component2 implements OnInit {
constructor(private sharedService: SharedService) {
this.sharedService.myData.subscribe((value) => {
console.log(value) // Here you will get your complete data
});
}
}
Upvotes: 1
Reputation: 739
in order to pass data between components in Angular, you should use Input and Output, there is a link below that it can help you find the deep understanding of passing data and event between component:
https://angular.io/guide/component-interaction
Upvotes: 0