如何将方法绑定到组件Angular?

时间:2019-06-12 12:11:25

标签: angular angular6 angular7

我在模板中使用子组件:

  <slide-panel
    (swipeleft)="onSwipeLeft($event)"
    (swiperight)="onSwipeRight($event)"
    [activePane]="isLeftVisible ? 'left' : 'right'">
</slide-panel>

如您所见,我使用输入activePane并从父组件传递内部变量isLeftVisible

此变量的更改方式是:

 public onSwipeLeft(event: any) {
    this.isLeftVisible = true;
  }

  public onSwipeRight(event: any) {
    this.isLeftVisible = false;
  }

我想使此组件隔离,并在其中移动所有功能onSwipeLeft,onSwipeRight。

现在,子组件取决于父变量isLeftVisible

因此,在使用该组件的所有地方,我都应该创建isLeftVisible

我可以绑定(swipeleft)="onSwipeLeft($event)",但将处理程序onSwipeLeft移动到组件内部吗?

1 个答案:

答案 0 :(得分:0)

您可以使用[EventEmitter][1]

您可以在子级中这样做:

@Output() open: EventEmitter<any> = new EventEmitter();

//in the method that creates the events you do

this.open.emit(//your parameters);

和你父亲一样

<.... (open)="handleopenEvent(e)" ....>

在父亲.ts中,您可以这样做:

public handleopenEvent(any:e){}