Roxy Roxy - 24 days ago 7
TypeScript Question

communication between two different components for data exchange/use: Angular 2

this is my view part:

<div>
<div class="customer">
<customer></customer>
</div>
<div class="addressAndPhases">
<address></address>
</div>
</div>


Customer component is getting the customer data and address data from the Server.

CustomerComponent

export class CustomerComponent extends SuperChildComponent {
public static url: string = 'orderViewCustomer';
public id;
public allowed: boolean = false;
public accessLevel: AccessLevel = null;
public componentname: string;
public customerData: Customer = null;

constructor(private rest: REST, private authenticationService: AuthorizationService) {
super();
this.componentname = this.constructor.name;
this.accessLevel = this.authenticationService.isUserLoggedIn() ? this.authenticationService.componentAccessLevel(this.constructor.name) : null;
console.log(this.constructor.name + ' has ' + this.accessLevel);
if (this.accessLevel == AccessLevel.ENABLED) {
this.getData();
}
}

private getData(): any {
this.rest.get(CustomerComponent.url,this.id).subscribe(data=> this.storeData(data.json()), err => console.log(err) ,()=> this.accessLevel==AccessLevel.DISBLED);

}



private storeData(res: Object): any {
this.customerData =<Customer>res;

}


}
class Customer {
id: string = null;
oldId: string = "";
firstName: string = "";
lastName: string = "";
email: string = "";
addressLine1: string = "";
addressLine2: string = "";
addressLine3: string = "";
street1: string = "";
street2: string = "";
postalCode: string = "";
city: string = "";
title: string = "";
gender: string = "";

}


Now in address component i want to use some data from component data like this:

<div [ngSwitch]="accessLevel">
<div class="addressAndPhases" *ngSwitchCase="'ENABLED'">
<h2 class="label">Address</h2><br>
<span>{{addressData.addressLine1}}</span><br>
<span>{{addressData.email}}</span>
</div>
</div>


this is how i am trying which is not a right way .

AddressComponent

export class AddressComponent implements OnInit {

public customer:CustomerComponent;
public addressData;
constructor() {
this.addressData=this.customer.customerData;

}


Problem : I am not sure how can i pass the data from Customer component to address component.

Can i inject customer component into address component's constructor ?

Please give your inputs. Thanks

Answer

I think you are looking for the @input and @output decorators ; and the EventEmitter class. Learn more about it in the component interaction documentation.

You could also do this with a shared service.