首页 文章

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

提问于
浏览
0

在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');
    }
}

这样可以正常工作,但有没有办法直接向父进行"passthrough"操作,而无需在调用 .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 回答

  • 1

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

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

    这是DEMO

相关问题