Onchanges Angular4无法正常工作

时间:2018-08-17 02:34:42

标签: angular

我的代码在onInit上有效,但在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[];
        });
}

我尝试遵循针对角度4的指南https://www.concretepage.com/angular-2/angular-2-4-onchanges-simplechanges-example

相同的代码正在与onInit一起使用,但我需要它来监视onChanges所做的更改

2 个答案:

答案 0 :(得分:0)

当对组件的输入属性进行数据绑定更改时,将自动调用诸如ngOnChanges之类的角度生命周期挂钩方法。

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

更改输入属性,并查看控制台ngOnChanges的调用方式

答案 1 :(得分:-1)

这是一个可能对您有帮助的示例

component.html

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

component.ts

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