I have a two sibling component like app-event and app-object inside one root component and I have array of objects inside app-object component ,now i want to pass that array of object in app-event sibling component, how can i do that in angualr2/4 in very simple way?
<div class="jumbotron">
<div class="container">
<div class="col-sm-8 col-sm-offset-2">
<app-object></app-object>
<app-event></app-event>
</div>
</div>
this is my model file
export class dataObject{
constructor(public item:string, public amount : number, public available:boolean){
}
}
this is app-object component ts file
import { Component, OnInit } from '@angular/core';
import { dataObject} from './app-object.model'
@Component({
selector: 'app-object',
templateUrl: './app-object.component.html',
styleUrls: ['./app-object.component.css']
})
export class AppObjectComponent implements OnInit {
data:dataObject[]=[new dataObject('itemA',45,true), new dataObject('itemB',58,false)];
constructor() {
console.log(this.data);
}
ngOnInit() {
}
}
Now the app-event component ts file code where i want to have the data of app-object file(data variable-array of object)
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-event',
templateUrl: './app-event.component.html',
styleUrls: ['./app-event.component.css']
})
export class AppEventComponent implements OnInit {
// here inside this class i want to have data of app-object component....
constructor() { }
ngOnInit() {
}
}
<app-object #obj></app-object>
<app-event [data]="obj.data"=></app-event>
AppEventComponent
needs
@Input()
data:dataObject[];
for this to work.
Use @ViewChild
to achieve this
<div class="jumbotron">
<div class="container">
<div class="col-sm-8 col-sm-offset-2">
<app-object></app-object>
<app-event></app-event>
</div>
</div>
Create two ViewChild() objects
as below
@ViewChild(AppObjectComponent) appObjectComponent : AppObjectComponent;
@ViewChild(AppEventComponent) appEventComponent : AppEventComponent;
Declare the variables as public so that it can be accessed from here.
In your AppObjectComponent
arrayVariable:any[];
In your AppEventComponent
array2:any[]
The method in your parent component will be as
someEvent(){
this.appObjectComponent.arrayVariable = this.appEventComponent.array2 ;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.