Passing/emitting 事件传递到父组件?
Passing/emitting events through to parent component?
在 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');
}
}
事件立即发送给父级,而无需通过子处理程序。当您只需单击要让父组件处理的子组件中的事件时,这很有用。
绝对可以从模板文件发出事件。事实上,当它是单行代码时,我也会这样做。这也很容易阅读。
<button (click)='onChildAction.emit($event)'>Click Me</button>
这是一个DEMO
在 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');
}
}
事件立即发送给父级,而无需通过子处理程序。当您只需单击要让父组件处理的子组件中的事件时,这很有用。
绝对可以从模板文件发出事件。事实上,当它是单行代码时,我也会这样做。这也很容易阅读。
<button (click)='onChildAction.emit($event)'>Click Me</button>
这是一个DEMO