将变量从子级传递到父级组件

时间:2020-07-04 14:57:19

标签: angular

因此,我尝试从子组件中获取一个值以在父组件中打印,并且尝试了以下操作:

在我的子组件ts中:

export class ChildComponent  {
 message: string = 'Hello!!!'; 
}

在我的父组件中ts:

import { Component, ViewChild, AfterViewInit} from '@angular/core';
import { ChildComponent } from '../child/child.component'

 export class ShoppingCartComponent implements ControlValueAccessor, AfterViewInit  {
  messageFromChild : string;
  @ViewChild(ChildComponent) myChild;
  ngAfterViewInit() {
    this.messageFromChild = this.myChild.message;
  }
  }

在我的父组件html中:

<h1> From Child - {{ messageFromChild }}  </h1>

{{messageFromChild}}为空。

我遵循的教程说过将父组件添加到app.module.ts中的bootstrap数组中,但是当我这样做时,我得到了一个空白页。

在控制台中,出现错误:TypeError:无法读取未定义的属性“ message”

1 个答案:

答案 0 :(得分:1)

您将需要使用@OutputEventEmitter

import { Output, EventEmitter } from '@angular/core';

export class ChildComponent  {
@Output() message: EventEmitter<string> = new EventEmitter<string>();
}

现在在您的任何方法内/根据您child.component.ts中的逻辑,做

someMethod() {
this.message.emit('Hello');
}

现在,在父组件html中,

<app-child (message)="onMessageReceived($event)"> </app-child>

最后,在父ts中,

onMessageReceived(message) {
console.log(message);
}

如果您仍然遇到问题,请选中此stackblitz