【问题标题】:Angular 5 Update Parent Component value from child ComponentAngular 5从子组件更新父组件值
【发布时间】:2018-07-15 01:05:18
【问题描述】:

子组件 TS

import { Component, OnInit, Input, Output } from '@angular/core';
import { EventEmitter } from 'events';

export class ChildComponent implements OnInit {
    @Output() OpenScheduleCall = new EventEmitter<boolean>();

    onLog() {
          this.OpenScheduleCall.emit(false);
    }
}

父组件 HTML:

<div [(hidden)]="OpenScheduleCall">
// content
</div>
<app-schedule-call *ngIf="!!OpenScheduleCall" [prospectid]='prospectid'  [(OpenScheduleCall)]="OpenScheduleCall"></app-schedule-call>

我在子组件中设置值,但更改未反映在父组件中

【问题讨论】:

    标签: angular typescript angular-components


    【解决方案1】:

    您尚未将OpenScheduleCall 标记为子组件的输入,因此首先您需要这样做。并且要实现与盒子里的香蕉的双向绑定,你的@Output需要是@Input变量名,后缀为Change。所以首先将变量OpenScheduleCall 标记为@Input 为child,然后更改@Output 变量的名称:

    export class ChildComponent implements OnInit {
    
      @Input() OpenScheduleCall;
      @Output() OpenScheduleCallChange = new EventEmitter<boolean>();
    
      onLog() {
       this.OpenScheduleCallChange.emit(false);
      }
    }
    

    现在你有了双向绑定:

    [(OpenScheduleCall)]="OpenScheduleCall"
    

    【讨论】:

    • 对此新手的注意:这仅在输入/输出变量名称匹配时有效,但输出末尾有Change。在此示例中,将输出命名为 OpenScheduleCallEvent不起作用
    • @ChrisBarr 我相信我在回答中已经提到了这一点,可能不够清楚(?)但感谢您的意见! :)
    • 大声笑,你是对的 - 对不起!我只是在没有阅读您的描述的情况下使用了您的代码,根据自己的喜好更改了 var 名称,然后记住了这个技巧并将其发布在这里。
    【解决方案2】:

    只是Output 不能在双向数据绑定中。在有界函数末尾添加()

    (OpenScheduleCall)="YourFunctionInParent($event)"
    

    【讨论】:

    • 我必须设置变量值OpenScheduleCall = false。我必须为此编写一个 setter 函数。?
    • 输出需要从孩子那里获取数据。你的子组件只有Output参数,所以只能绑定()
    • 我还是很困惑,YourFunctionInParent 什么时候会触发。你能改变我的代码吗?或建议任何有效的 plnkr。
    • YourFunctionInParent 将在子级中的OpenScheduleCall 发出时触发
    猜你喜欢
    • 2018-09-14
    • 2021-02-10
    • 2021-08-30
    • 2017-05-03
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    相关资源
    最近更新 更多