![](/img/trans.png)
[英]Binding data to another component and use it in angular using @Input, @Output and EventEmitter
[英]Angular: How to send string values to another component using EventEmitter?
我有一个父组件和一个子组件,我想通过 EventEmitter 从子组件发送 2 个值到父组件,因为我想在那里使用 printMessages() 函数。
我在子组件上有一个单击事件,它发出 2 个字符串值,但我不确定如何将发出事件连接到父组件以及如何运行 printMessages() 函数。 父组件如何将这些值读入“printMessages()”函数并让该函数在值到达它之后运行? 如您所见,我目前在父组件中没有 HTML,也许我需要在那里做点什么?
父组件:
import { Component } from '@angular/core';
@Component({
selector: 'parent-component',
template: ``,
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
constructor() { }
// Function in which I want to send values from the child component.
printMessages(string1: string, string2: string) {
console.log(string1, string2);
}
子组件:
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'child-component',
template: `
<button (click)="sendStrings()">Send Strings</button>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Output() message = new EventEmitter();
constructor() { }
sendStrings(){
this.message.emit({string1:"Hello", string2:"World!"});
}
}
您需要对模板中的子组件事件做出反应并调用该方法。
import { Component } from '@angular/core';
@Component({
selector: 'parent-component',
template: `<child-component (onMessage)="printMessages(e)"></child-component>`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
constructor() { }
printMessages(event) {
// strings are included in event object
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.