0

I have 2 components, onclick of button of 1st component the value (any string) should be added to the array of the 2nd component. How can i achieve this? I work on angular 4.

@Component({
  selector: 'app-sibling',
  template: `
    {{message}}
    <button (click)="newMessage()">New Message</button>
  `,
  styleUrls: ['./sibling.component.css']
})
newMessage() {
    console.log("button clicked");
  }
5
  • What's the relationship between these components? Parent-child? Siblings? Commented May 17, 2018 at 9:06
  • 2
    Use a service (based on observables) to comlunicate between the 2 components if they are not parent/child, otherwise use Input/Output Commented May 17, 2018 at 9:07
  • is it parent /child relationship Commented May 17, 2018 at 9:10
  • Have a look at the official docs about it: angular.io/guide/component-interaction Commented May 17, 2018 at 9:12
  • use Component Interaction Commented May 17, 2018 at 9:58

1 Answer 1

1

You are primarily looking to communicate between two components,

You can use a service with Array. A service in Angular is a singleton, meaning it is managed as a single instance. So if each of the components access the service, they will access the same shared data.

export class cartService{
    prod :any = [];        
    UpdateArray (newObject: any) {
        this.prod.push(newObject);         
    }
}

In your component you can do this,

  this._cartService.UpdateArray(this.prod);

any can be replaced with your object type

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.