【问题标题】:Onchanges Angular4 not workingOnchanges Angular4 不起作用
【发布时间】:2019-01-24 00:59:05
【问题描述】:

我的代码在 Init 上工作,但在 onChanges 上没有。

这是来自组件的代码

import { Component, Input, OnInit, OnChanges, SimpleChanges } from '@angular/core';

export class FetchDataComponent implements OnChanges  {
 site: string[] = [];
 @Input() values: string = "https://angular.io";    

 onEnter(value: string) { this.values = value; } // this is to get value from input field

ngOnChanges(changes: SimpleChanges) {

 var slog = this.values;

 this._httpService.get('/api/websites/?angular='+slog).subscribe(values => {
            this.site= values.json() as string[];
        });
}

我尝试按照指南 https://www.concretepage.com/angular-2/angular-2-4-onchanges-simplechanges-example 进行操作,该指南针对角度 4。

相同的代码正在使用 onInit,但我需要它来监控对 onChanges 所做的更改

【问题讨论】:

  • 你能在改变这个组件的输入的地方添加代码吗?
  • 所以你的意思是说ngOnChanges() 没有被解雇?您是否尝试添加 console.log() 并检查过?

标签: angular


【解决方案1】:

当组件的输入属性上的数据绑定更改时,像 ngOnChanges 这样的角度生命周期钩子方法将自动调用。

请检查这些 stackblitz URL https://stackblitz.com/edit/angular-hpshn4?file=src%2Fapp%2Femployee%2Femployee.component.ts

更改输入属性并查看控制台如何调用 ngOnChanges

【讨论】:

    【解决方案2】:

    这是一个可能对你有帮助的例子

    component.html

    <select placeholder="A" (selectionChange)="appslctchange($event)">
    

    component.ts

     appslctchange(changeEvent) 
             {
              alert("It Works");
             }
    

    【讨论】:

      猜你喜欢
      • 2016-06-06
      • 1970-01-01
      • 2018-10-14
      • 2017-12-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2017-12-04
      • 1970-01-01
      相关资源
      最近更新 更多