K
K
Kerim Berdimyradov2017-02-08 00:22:26
JavaScript
Kerim Berdimyradov, 2017-02-08 00:22:26

How to catch event in child component?

Angular2 has a component, let's say ParentComponent

@Component({
  selector: 'parent',
  template: `<section>
  <my-cool-child-component></my-cool-child-component>
  <button (click)="clickMe()"></button>
</section>`,
  styles: ``,
})
export class ParentComponent  {
  clickMe() {
            //When button is clikced maybe tregger an event, which is need to be caught in child component
  }
}

On button click, I want the child component to change its state
@Component({
  selector: 'my-cool-child-component',
  template: `<div><h1>{{state}}</h1></div>`,
  styles: ``,
})
export class MyCoolChildComponent  {
  private state = 'default';

//On parent button clicked need to change the state
}

Is it possible in the child component to catch the button click event from the parent component so I can change the state value in the child component?
Thanks in advance

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel Shvedov, 2017-02-08
@mmmaaak

Bad architecture. A component, it should not know about someone, or about something, outside of itself. It should only give out some kind of interface so that it can be controlled by the parent. What you want to do is store in the parent and pass it to the child, like the @Input() property, that should change in the child components. And when you click in the parent, change this data, and it will be updated in the child component

G
Gorovalo, 2017-02-09
@Gorovalo

parent component

@Component({
  selector: 'parent',
  template: `<section>
  <my-cool-child-component [state]="someData"></my-cool-child-component>
  <button (click)="clickMe()"></button>
</section>`,
  styles: ``,
})
export class ParentComponent  {
someData; 

 clickMe() {
            this.someData = ...;
  }
}

child component
import { Input } from '@angular/core';

@Component({
  selector: 'my-cool-child-component',
  template: `<div><h1>{{state}}</h1></div>`,
  styles: ``,
})
export class MyCoolChildComponent  {
  @Input() state;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question