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); } }); } }
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.
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.
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.
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)"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With