Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 call parent method in a child component

Tags:

angular

I want to call parent method (deletePhone) in child component in Angular 4. How can I do that properly?

my parent component looks like:

export class ContactInfo implements OnInit {     phoneForm: FormGroup;     phones: Phone[];       constructor(private fb: FormBuilder,             private userService: UserService) {     }      ngOnInit() {         this.userService.getDataPhones().subscribe(             phones => {                 this.phones = phones;             });          this.phoneForm = this.fb.group({             phone: ['', [Validators.pattern(PHONE_PATTERN)]]         });     }      deletePhone(phone: Phone) {         this.userService.deleteUserPhone(phone)             .subscribe(res => {                 let index = this.phones.indexOf(phone);                 if (index > -1) {                     this.phones.splice(index, 1);                 }         });     } } 
like image 627
Ihor Lavs Avatar asked Apr 10 '17 12:04

Ihor Lavs


People also ask

Can I call parent component method from child Angular?

To call a parent component method from a child component, you need to use an Angular EventEmitter. Emitting events allows your components to communicate with one another when a certain action has been executed, in this example the action is on click.

How do you call a method in parent component from a child component?

Call Parent Component method from Child Component For Calling Parent Component method from Child Component, I had created a method getParentMethod and in this method, I had set input property in HTML file of parent component. Then shown as below code inside the child component I am able to access parent method.

How do you call parent method from child object?

If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super to call the parent method, inside the body of the child method.


1 Answers

import { Output, EventEmitter } from '@angular/core';   ...  class ChildComponent {   @Output() someEvent = new EventEmitter<string>();    callParent(): void {     this.someEvent.next('somePhone');   } } 

In ContactInfo's template

<child-component (someEvent)="deletePhone($event)" 
like image 200
Günter Zöchbauer Avatar answered Oct 06 '22 00:10

Günter Zöchbauer