将事件从子组件传递到父组件Angular 5 [英] Pass Event from child component to parent component Angular 5

查看:71
本文介绍了将事件从子组件传递到父组件Angular 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为program-page的父组件,它有一个名为program-item的子组件,现在我在program-item上有一个按钮,而我希望该按钮要做的是在父组件上调用一个函数.我不知道我会怎么做这样的事情.

program-page.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

someFunction()

program-item.component.html

<button>click me</button> // button I want to be able to call event on parent component

我知道我可以使用一个事件发射器,但是我以前从未使用过一个事件发射器,并且不确定在这种情况下如何实现它,我还没有看到在子组件上单击按钮调用父组件上的函数的任何示例

任何帮助将不胜感激!

解决方案

Angular具有Input和Output,可用于向子组件提供数据并将事件分别发送给父组件.

您可以执行以下操作.

program-page.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

import { EventEmitter } from '@angular/core';
....
@Output() someEvent = new EventEmitter();

program-item.component.html

<button (click)="someEvent.emit('data')">click me</button>

原始使用输入和输出 Stackblitz示例

I have a parent component called program-page and it has a child component called program-item now I have a button on the program-item and 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.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

someFunction()

program-item.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!

解决方案

Angular has Input and Output, which can be used to provide data to a child component and send events to a parent component respectively.

You can do something like this.

program-page.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

import { EventEmitter } from '@angular/core';
....
@Output() someEvent = new EventEmitter();

program-item.component.html

<button (click)="someEvent.emit('data')">click me</button>

Primitive usage of Input and Output Stackblitz example

这篇关于将事件从子组件传递到父组件Angular 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆