Answer the question
In order to leave comments, you need to log in
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
}
}
@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
}
Answer the question
In order to leave comments, you need to log in
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
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 = ...;
}
}
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 questionAsk a Question
731 491 924 answers to any question