【问题标题】:Angular Child to Parent interactionAngular 孩子与父母的互动
【发布时间】: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}}。我在这里遗漏了什么吗?

【问题讨论】:

标签: angular typescript


【解决方案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

【讨论】:

    猜你喜欢
    • 2021-04-25
    • 2019-02-04
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    相关资源
    最近更新 更多