本文介绍了子组件中的Angular 4调用父方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Angular 4的子组件中调用父方法(deletePhone).我该怎么做呢?

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

我的父组件看起来像:

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);
                }
        });
    }
}

推荐答案

import { Output, EventEmitter } from '@angular/core';

...

class ChildComponent {
  @Output() someEvent = new EventEmitter<string>();

  callParent(): void {
    this.someEvent.next('somePhone');
  }
}

ContactInfo的模板中

<child-component (someEvent)="deletePhone($event)"

这篇关于子组件中的Angular 4调用父方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 11:33