Angular 孩子与父母的互动
Posted
技术标签:
【中文标题】Angular 孩子与父母的互动【英文标题】:Angular Child to Parent interaction 【发布时间】:2021-02-18 15:58:47 【问题描述】:在这里,我从子级发出一个事件,并试图在父级 html 中显示它,但我认为这不起作用。这是我的代码
父组件.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);
父组件 HTML
<app-child [childMessage] = "parentMessage" (sendingToParent) = "fromChild($event)"></app-child>
<p>fromChildMessage</p>
子组件.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);
子组件 HTML
<p>child works!</p>
childMessage
<button (click)="sendParent()">SEND</button>
在上面的代码中,当我显示 ParentComponent.HTML 时,我没有看到 fromChildMessage
没有在浏览器中打印,而且我在显示 ChildComponent.HTML 时也没有看到 childMessage
。我在这里遗漏了什么吗?
【问题讨论】:
看看这个stackblitz 【参考方案1】:在子组件中设置 EventEmitter 为字符串
@Output() sendingToParent: EventEmitter<string> = new EventEmitter<string>();
然后在父组件上:
fromChild(eventValue)
this.fromChildMessage = eventValue;
console.log(this.fromChildMessage);
阅读更多:https://medium.com/@Zeroesandones/emit-an-event-from-a-child-to-parent-component-in-angular-9-7c3690c75f6
【讨论】:
以上是关于Angular 孩子与父母的互动的主要内容,如果未能解决你的问题,请参考以下文章