我想在 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');
}
}
在ContactInfo
的模板中
<child-component (someEvent)="deletePhone($event)"
关于Angular 4在子组件中调用父方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43323272/