Quiero llamar al método principal (deletePhone) en el componente secundario en Angular 4. ¿Cómo puedo hacerlo correctamente?
mi componente principal se parece a:
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'); } } En la plantilla de ContactInfo
<child-component (someEvent)="deletePhone($event)"Esto funcionó para mí (ejemplo de documentos oficiales):
https://angular.io/api/core/EventEmitter#ejemplos
Niño:
@Component({ selector: 'zippy', template: ` <div class="zippy"> <div (click)="toggle()">Toggle</div> <div [hidden]="!visible"> <ng-content></ng-content> </div> </div>`}) export class Zippy { visible: boolean = true; @Output() open: EventEmitter<any> = new EventEmitter(); @Output() close: EventEmitter<any> = new EventEmitter(); toggle() { this.visible = !this.visible; if (this.visible) { this.open.emit(null); //emit event here } else { this.close.emit(null); } } }Padre:
<zippy (open)="onOpen($event)" (close)="onClose($event)"></zippy>No me gusta el código repetitivo como @Output(). Encontré otra solución, simplemente pase el objeto con cualquier cantidad de funciones anónimas
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-parent', styleUrls: ['./parent.component.css'], template: ` <app-child [parentApi]="getParentApi()"></app-child> `, }) export class ParentComponent implements OnInit { getParentApi(): ParentComponentApi { return { callParentMethod: (name) => { this.parentMethod(name) } } } constructor() { } ngOnInit() { } parentMethod(name: string) { console.log(`Hello ${name} from parent`) } } export interface ParentComponentApi { callParentMethod: (string) => void }y niño:
import { Component, OnInit, Input } from '@angular/core'; import { ParentComponentApi } from '../parent/parent.component'; @Component({ selector: 'app-child', template: `<button (click)="callParent()">call parent</button>`, styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit { @Input() parentApi: ParentComponentApi constructor() { } callParent() { this.parentApi.callParentMethod("child") } ngOnInit() { } }Creo que es bastante seguro hacerlo de esta manera, ¿no?