角孩子与父母的互动

时间:2020-11-05 21:47:51

标签: angular typescript

在这里,我正在从孩子那里发出一个事件,并试图在“父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}}。我在这里想念东西吗?

1 个答案:

答案 0 :(得分:0)

在子组件中,将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