首页 文章

孩子不检测父改变Angular 2

提问于
浏览
1

嗨,我有一个问题,它是如何工作的 . 我有一个2组件父和子(我只显示一段代码,因为它是我的工作项目) .

所以模板的父组件:

<product-empty [showHistoryMonth]="showHistoryMonth" [showHistoryAvg]="showHistoryAvg"
           [SP_L_FCSQData]='SP_L_FCSQData'
           [allHistoryAvgNames]="allHistoryAvgNames" [salesPlanId]="salesPlanId" [allHistoryChannels]="allHistoryChannels" [airingsNames]="airingsNames"
           [allForecastMonthChannels]="allForecastMonthChannels" [forecastShows]="displayArry"
           [allProductSummary]="allProductSummary"  ></product-empty>

和在这种情况下重要的功能:

private displayArry: string[] = [];

getForecastDisplay(emit: any) {
        if (emit.show) {
            var index = this.displayArry.indexOf(emit.id);
            if (index === -1) {
                this.displayArry.push(emit.id);
            } else { }
        } else {
            var index = this.displayArry.indexOf(emit.id);
            this.displayArry.splice(index, 1);
        }
        this.forecastShows = emit;
        console.log('forecast show', this.displayArry);
    }

和子组件:

export class FlexProductEmptyComponent implements DoCheck, OnInit, OnChanges {
    ...
    @Input() showHistoryMonth: boolean = false;
    @Input() showHistoryAvg: boolean = false;
    @Input() forecastShows: any;
    ...

所以问题是数据如何传递给父母和孩子 . 现在我尝试检测孩子的父变化 . 编辑:当其他组件发出数据并更新displayArry时,将调用getForecastDisplay函数 . 所以我认为当displayArry变量被更改时,会再次传递给绑定到父级的所有子项 .

我的意思是我试图 grab 父数据发生变化并将其传递给孩子的那一刻 . 我使用了一个setter,当我在它上面设置一个控制台日志时,它只能在init上登录 . 我使用OnChanges进行简单的更改,只在组件启动时记录;但是更改时的数据会传递给子组件(我知道它因为我在doCheck中设置了一个控制台日志并且它显示了正确的值) .

所以主要问题是当父组件将更改数据传递给子时,我如何能够 grab 那一刻?

1 回答

  • 2

    有许多方法可以实现父组件和子组件之间的通信,最明显的方法是通过input and output properties或通过服务 . 可观察是另一种选择 . 这是an example with BehaviorSubject(a special kind of Observable) . 步骤如下:

    • 'new'父级中的BehaviorSubject,我们将其命名为 someRxx .

    • 使用输入属性将BehaviorSubject传递给child,如 <my-child [nameRxx]="someRxx"></my-child> .
      在子模板中

    • ,使用异步管道,如 <h2>Hello {{nameRxx | async}}</h2> ;或者在子组件中,你做 nameRxx.subscribe(doSomething) (不要忘记在ngOnDestroy中取消订阅)
      在父组件或其模板中

    • ,执行 someRxx.next(value) ,只要您执行 .next ,子项就会收到该值 .

    请享用 .

相关问题