Angular 4 - calling parent method from child component not working
All my event emitters are working correctly except for one.
child.ts:
@Component({
...
outputs: ['fileUploaded']
})
export class childComponent implements OnInit {
...
fileUploaded = new EventEmitter<boolean>();
...
randomMethod(){
...
this.fileUploaded.emit(true);
}
}
randomMethod () is called from the parent component, as I show in parent.ts. It is not called in child.html.
parent.html
...
<child (fileUploaded)="onSubmit($event)"></child>
..
parent.ts
export class parentComponent {
...
theChild = new childComponent;
submitted = false;
...
onSubmit(event: boolean) {
console.log('in onSubmit()');
this.submitted = event;
}
functionCallsChild(){
this.theChild.randomMethod();
...
this.theChild = new childComponent;
}
}
My application never writes to "onSubmit ()", so why isn't this method called? I also tried not to create a new child on my last line, but that had no effect.
source to share
Your child component is wrong, you must use ViewChild
like this:
parent.html:
<child #theChild (fileUploaded)="onSubmit($event)"></child>
parent.ts:
export class parentComponent {
...
@ViewChild('theChild') theChild;
submitted = false;
...
onSubmit(event: boolean) {
console.log('in onSubmit()');
this.submitted = event;
}
functionCallsChild(){
this.theChild.randomMethod();
...
}
}
source to share
I may not understand why you are choosing this approach or what you need it for, but as far as I know you should be using EventEmitter
from child to parent. This means that the event that fires .emit () shold is placed in child.html. Try this and it should work:
child.html
<div (click-or-whatever-fires-what-you-want)="randomMethod()"></div>
child.ts:
@Component({
...
})
export class childComponent implements OnInit {
...
@Output() fileUploaded = new EventEmitter<boolean>();
...
randomMethod(){
...
this.fileUploaded.emit(true);
}
}
parent.html
...
<child (fileUploaded)="onSubmit($event)"></child>
..
parent.ts
export class parentComponent {
...
submitted = false;
...
onSubmit(event: boolean) {
console.log('in onSubmit()');
this.submitted = event;
}
}
Hope this was helpful.
source to share
You can call the parent component's method from the child component using the @Output emitter, which fires any event on the child component. I used this approach in the comments section to update the score in the parent component using the child component method.
Parent.ts
/** Update the count from child component */
UpdateCount(id) {
this.getTotalCommentCountByGroupId(id);
}
Parent.HTML
<srv-group-feed [LiveFeedInput]="groupPostRes"
(CommentCount)="UpdateCount($event)"></srv-group-feed>
Child.ts
this.CommentCount.emit(data you need to pass);
and globally you can declare @Output event in child component ie child.ts
@Output() CommentCount = new EventEmitter<string>();
source to share