将事件传递/发送到父组件?

时间:2018-06-12 14:25:15

标签: angular angular-components

在Angular中,我可以创建一个发出动作的子组件:

@Component({
   ...
    template: `
      <button (click)='someAction($event)'>Click Me</button>
    `
})
export class ChildComponent {

    @Output() onChildAction = new EventEmitter();

    childAction() {
      this.onChildAction.emit();
    }
}

以及处理它的父组件。类似的东西:

@Component({
    ...
    template: `
      <child-component (onChildAction)="parentAction()"></child-component>
    `
})
export class ParentComponent {
    parentAction() {
      console.log('Hello');
    }
}

这种方法很好,但有没有办法通过&#34; passthrough&#34;直接对父进行操作而无需在调用.emit()的子进程中创建单击处理程序?

类似的东西:

@Component({
   ...
    template: `
      <button (click)='onChildAction.emit($event)'>Click Me</button>
    `
})
export class ChildComponent {
    @Output() onChildAction = new EventEmitter();
}

@Component({
    ...
    template: `
      <child-component (onChildAction)="parentAction()"></child-component>
    `
})
export class ParentComponent {
    parentAction() {
      console.log('Hello');
    }
}

将事件立即发送给父级,而不必通过子级处理程序。当您只需单击要让父组件处理的子项中的事件时,这非常有用。

1 个答案:

答案 0 :(得分:1)

绝对可以从模板文件中发出事件。实际上,当它是单行代码时,我也会这样做。这也很容易阅读。

<button (click)='onChildAction.emit($event)'>Click Me</button>

这是DEMO