Angular 4在子组件中调用父方法

2024-03-14

我想在 Angular 4 的子组件中调用父方法(deletePhone)。 我怎样才能正确地做到这一点?

我的父组件如下所示:

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

In ContactInfo的模板

<child-component (someEvent)="deletePhone($event)"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 4在子组件中调用父方法 的相关文章

随机推荐