首页 > 解决方案 > 在另一个组件中使用 @output 值

问题描述

我有一个发出值的组件@Output和另一个我想使用该值的组件。

我如何myValueOutputComponentInputComponent

输出组件

export class OutputComponent implements OnInit {
  @Output() myValue: EventEmitter<any> = new EventEmitter();
  ...
}

输入组件

export class InputComponent implements OnInit {
  // Use myValue here
}

标签: angular

解决方案


如果“输入组件”是父组件:

在 child.component.ts 中:

@Output() someEvent = new EventEmitter

someFunction(): void {
  this.someEvent.emit('Some data...')
}

在父模板中:

<app-child (someEvent)="handleSomeEvent($event)"></app-child>

在 parent.component.ts 中:

handleSomeEvent(event: any): void {
  // Do something (with the event data) or call any functions in the component
}

如果它是一个不相关的组件,您需要使用您可以从应用程序中的任何位置订阅的主题将服务绑定到应用程序的根目录。

我在这里记录了组件之间所有类型的数据共享:

https://github.com/H3AR7B3A7/EarlyAngularProjects/tree/master/dataSharing


推荐阅读