EventEmitter类的清晰概念 [英] Clear concept of EventEmitter Class
问题描述
编码到子组件mycomponent.ts
code into child component mycomponent.ts
import { Component, OnInit , EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-mycomponent',
template: `
<button (click)="clickchild()">Click me!</button>
`
})
export class MycomponentComponent {
@Output() clicked = new EventEmitter<string>();
clickchild() {
this.clicked.emit('This is Child Component Code!');
}
}
将数据传递到父组件app.component.ts
Passing data into parent component app.component.ts
import { Component , EventEmitter, Output } from '@angular/core';
import { MycomponentComponent } from './mycomponent.component';
@Component({
selector: 'app-root',
template: `
<h2>sdsd</h2>
<app-mycomponent (clicked)="onClicked($event)"></app-mycomponent>
<p>{{childdata}}</p>
`
})
export class AppComponent {
childdata= '';
onClicked(value: string) {
this.childdata = value;
}
}
我的问题是->
为什么我们再次定义onClicked函数并将字符串传递给Parent Component,
why we again define onClicked function and pass a string into Parent Component ,
childdata ='';
childdata= '';
onClicked(value: string) {
this.childdata = value;
}
尽管我们已经在子组件中做到了,但我们已经在其中定义了功能
although we have already did that in to child component we have defined function there
clickchild() {
this.clicked.emit('This is Child Component Code!');
}
推荐答案
Child组件发出click事件.您的子组件的click事件会发出一个字符串,如您在此处定义的那样:
The Childcomponent emits a click event. The click event of your childcomponent is emitting a String, as you defined here:
@Output() clicked = new EventEmitter<string>();
clickchild() {
this.clicked.emit('This is Child Component Code!');
}
可以通过$ event参数访问事件的有效负载(在这种情况下为字符串).您可以通过以下方式预订父组件的click事件:
The payload of the event (a string in this case), can then be accessed by the parameter $event. You subscribe in your parent component to the click event by:
<app-mycomponent (clicked)="onClicked($event)"></app-mycomponent>
onClicked(value: string) {
this.childdata = value;
}
因此,子组件会发出click事件,但必须由父组件识别(利用订阅),否则父组件将不知道所发出的事件.
So the child component emits a click event, but it has to be recognized by the parent component (utilizing subscription), otherwise the parent would not know about the emitted event.
有关文档,请参见此处: https://angular.io/api/core/EventEmitter
See here for the docs: https://angular.io/api/core/EventEmitter
Sagat
这篇关于EventEmitter类的清晰概念的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!