【问题标题】:Angular 7: passing parameters to other component errorAngular 7:将参数传递给其他组件错误
【发布时间】:2023-03-13 07:26:01
【问题描述】:

我有 2 个组件,一个父组件和一个子组件,我想将变量的值发送到父组件,我尝试了下面的代码但没有成功。子组件正确发送信息,但是父组件没有接收,看来父组件中的函数没有识别接收到要触发的数据。

子组件

...

private elements:any;
@Output() element = new EventEmitter<any>();


 constructor() {

 }

  ngOnInit() {
    this.sendContent();
  }


 sendContent() {
    this.elements = "hi";

    console.log("sended");
    console.log(this.elements);

    this.element.emit(this.elements);
    //the function is activated and I can see the return in the console
  }

父组件

...

constructor() {

}

ngOnInit() {

}

receiveContent(elements) {
    console.log("received");
    console.log(elements);
    //the function is not activated when the child component is sent the data
 }

父模板

<app-child (sendContent)="receiveContent($event)"></app-child>

谢谢。

【问题讨论】:

    标签: javascript angular typescript events components


    【解决方案1】:

    您应该在括号内放置使用@Output 装饰器装饰的属性的名称。在这种情况下(元素)

    将您的 parent.html 更改为:

    <app-child (element)="receiveContent($event)"></app-child>
    

    【讨论】:

      【解决方案2】:

      在您的父组件中,您需要绑定到来自子组件的正确事件。

      在您的子组件中,您将 Output() 声明为 element,因此在这种情况下,父组件中使用的正确 event 名称将是 element

      正确的代码是:

      <app-child (element)="receiveContent($event)"></app-child>
      

      Official Angular Documentation - Component Interaction

      【讨论】:

        猜你喜欢
        • 2018-03-30
        • 2018-12-11
        • 1970-01-01
        • 1970-01-01
        • 2019-06-10
        • 2021-08-15
        • 2019-04-03
        • 2019-12-29
        • 2021-11-15
        相关资源
        最近更新 更多