Angular 2 - how can a child component speak to a parent component?
I used @input for parent to child which works fine.
What would I use to do child to parent?
This is my compiler error I get:
Angular 2 - how can a child component speak to a parent component?
I used @input for parent to child which works fine.
What would I use to do child to parent?
This is my compiler error I get:
You can use @Output
to trigger events from the child component. The parent one can register processing on them.
Here is a sample
@Component({
selector: 'child',
(...)
})
export class ChildComponent {
@Output()
someEvent: EventEmitter;
constructor() {
this.someEvent = new EventEmitter();
}
triggerEvent() {
this.someEvent.emit('some value');
}
}
and its use in the parent component:
<child (some-event)="printValue($event)"></child>
FYI $event
contains the value 'some value'
.
You can notice that Angular2 supports two-way binding at this level:
@Component({
selector: 'child',
(...)
})
export class ChildComponent {
@Input()
value:string
@Output()
valueChanges: EventEmitter;
constructor() {
this.valueChanges = new EventEmitter();
}
triggerUpdated() {
this.valueChanges.emit('some value');
}
}
and its use in the parent component:
<child [(value)]="someVar"></child>
Edit
To call a method from the parent component, you need to inject it into the child one.
You need to be careful at this level to cyclic dependency in imports and that hoisting isn't supported for classes (use a class before it's created).
See this answer for more details:
Here is a sample:
@Component({
selector: 'child',
(...)
})
export class ChildComponent {
constructor(@Inject(forwardRef(() => AppComponent)) parent:ParentComponent) {
(...)
}
}
This article could also give you some hints:
Thierry