在这里,我正在从孩子那里发出一个事件,并试图在“父HTML”中显示它,但是我看不到这个工作。这是我的代码
ParentComponent.ts
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss']
})
export class ParentComponent implements OnInit {
parentMessage = "Hello from Parent";
fromChildMessage: String;
constructor() { }
ngOnInit(): void {
}
fromChild($event){
this.fromChildMessage = $event;
console.log(this.fromChildMessage);
}
}
ParentComponent HTML
<app-child [childMessage] = "parentMessage" (sendingToParent) = "fromChild($event)"></app-child>
<p>{{fromChildMessage}}</p>
ChildComponent.ts
import { EventEmitter } from '@angular/core';
import { Component, Input, OnInit, Output } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {
@Input() childMessage: String;
@Output() sendingToParent: EventEmitter<any> = new EventEmitter<any>();
text: String = "Hello from Child";
constructor() { }
ngOnInit(): void {
}
sendParent(): any {
this.sendingToParent.emit(this.text);
}
}
ChildComponent HTML
<p>child works!</p>
{{childMessage}}
<button (click)="sendParent()">SEND</button>
在上面的代码中,当我显示ParentComponent.HTML时,没有看到{{fromChildMessage}}
没有在浏览器中打印,并且在我显示ChildComponent.HTML时也没有看到{{childMessage}}
。我在这里想念东西吗?
答案 0 :(得分:0)
在子组件中,将EventEmitter设置为字符串
@Output() sendingToParent: EventEmitter<string> = new EventEmitter<string>();
然后在父组件上:
fromChild(eventValue){
this.fromChildMessage = eventValue;
console.log(this.fromChildMessage);
}