从子组件调用父函数

时间:2019-11-29 13:16:24

标签: angular typescript ionic-framework ionic3

我具有以下结构。

ParentComponent.ts

reset(offense) {
    return this.http.post(...);
}   

ParentComponent.html

<ion-list>
    <swipable-offense-card
        *ngFor="let offense of filteredOffenses"
        [offense]="offense"
        (onReset)="reset(offense)"
        >
    </swipable-offense-card>
</ion-list>    

和孩子: ChildComponent.ts

@Component({
    selector: 'swipable-offense-card',
    templateUrl: 'swipable-offense-card.html',
  })
  export class SwipableOffenseCard {
    @Input() offense: Offense;
    @Output() onReset: EventEmitter<any> = new EventEmitter();

    reset() {
      this.onReset.emit();
    }
  }
}

ChildComponent.html

<p>{{ offense.title }}</p>
<button (click)="reset()"></button>

现在,通过这种结构,我在此处传递的(onReset)="reset(offense)"的encem参数被发送到父组件。但是,我更喜欢这样做。

ChildComponent.ts

reset() {
    this.onReset.emit({
       ...this.offense
    });
}

但是,这个没有发送任何参数来重置父组件的方法。如何在Angular中做到这一点?

1 个答案:

答案 0 :(得分:1)

您必须在这样的参数中添加$event

// ParentComponent.html
<ion-list>
  <swipable-offense-card
     *ngFor="let offense of filteredOffenses"
     [offense]="offense"
     (onReset)="reset($event)"
     >
 </swipable-offense-card>
</ion-list>

以下是示例https://stackblitz.com/edit/angular-dkfxb2