Javascript 将事件从子组件传递到父组件 Angular 5
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48897465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass Event from child component to parent component Angular 5
提问by Smokey Dawson
I have a parent component called program-pageand it has a child component called program-itemnow I have a button on the program-itemand what I want that button to do is to call a function on the parent component.. Im not sure how I would do something like this..
我有一个父组件被调用program-page,它有一个子组件被调用,program-item现在我有一个按钮,program-item我希望该按钮做的是调用父组件上的函数..我不知道我会如何做这样的事情。 .
program-page.component.html
程序页面.component.html
<app-program-header></app-program-header>
<app-week-display></app-week-display>
<app-program-item [item]="programItem"></app-program-item>
program-page.component.ts
程序页面.component.ts
someFunction()
program-item.component.html
程序项.component.html
<button>click me</button> // button I want to be able to call event on parent component
Im aware I could use an event emitter but Ive never used one before and not sure how I would implement it in this case, I havent seen any examples where clicking a button on a child component calls a function on the parent
我知道我可以使用事件发射器,但我以前从未使用过,并且不确定在这种情况下如何实现它,我还没有看到任何单击子组件上的按钮调用父组件上的函数的示例
any help would be appreciated!
任何帮助,将不胜感激!
回答by Pavan Bahuguni
Angular has Input and Output, which can be used to provide data to a child component and send events to a parent component respectively.
Angular 有 Input 和 Output,可以分别用来向子组件提供数据和向父组件发送事件。
You can do something like this.
你可以做这样的事情。
program-page.component.html
程序页面.component.html
<app-program-header></app-program-header>
<app-week-display></app-week-display>
<app-program-item [item]="programItem" (someEvent)="someFunction(data)"></app-program-item>
program-item.component.ts
程序项.component.ts
import { EventEmitter } from '@angular/core';
....
@Output() someEvent = new EventEmitter();
program-item.component.html
程序项.component.html
<button (click)="someEvent.emit('data')">click me</button>
Primitive usage of Input and Output Stackblitz example
输入和输出Stackblitz 示例的原始用法

