3

每当组件生命周期或模板中的变量发生更改但它不起作用时,我都会尝试ngOnChanges()在我的 Angular 5.x 组件中调用函数,但它不工作,函数不会随时被调用。请问有人可以帮我吗?this.testngOnChanges()

src/app.ts:

import {Component, NgModule, Input, OnChanges, SimpleChanges} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input type="text" placeholder="Test field" value="{{ test }}">
    </div>
  `,
})
export class App implements OnChanges {
  @Input() test: string;
  name: string;
  constructor() {
  }

  ngOnChanges(changes: SimpleChanges) {
    console.log('ngOnChanges');

    if (changes.test && !changes.test.isFirstChange()) {
      // exteranl API call or more preprocessing...
    }

    for (let propName in changes) {
      let change = changes[propName];
      console.dir(change);
      if(change.isFirstChange()) {
        console.log(`first change: ${propName}`);
      } else {
        console.log(`prev: ${change.previousValue}, cur: ${change.currentValue}`);
      }
    }
  }


}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

实时预览:https ://plnkr.co/edit/ZHFOXFhEkSv2f1U3lehv

非常感谢!

4

2 回答 2

7

输入属性为父组件提供了一种将数据传递给子组件的机制。它们并不意味着将数据从模板传递到其组件。

只有对 PARENT 定义的输入属性的更改才会生成 onChanges 方法。

我更新了 plunker 以修复丢失的 FormsModule 并添加一个子组件来演示如何使用 input 属性和 onChanges 生命周期挂钩:

https://plnkr.co/edit/1JF0wV28HnjXDZxMSifY?p=preview

子组件

@Component({
  selector: 'my-child',
  template: `
    <div>
      <input type="text" [(ngModel)]="test" placeholder="Test field">
    </div>
  `,
})
export class ChildComponent implements OnChanges {
  @Input() test: string;
  name: string;
  constructor() {  }

  ngOnChanges(changes: SimpleChanges) {
    console.log('in ngOnChanges');
    if (changes.test && !changes.test.isFirstChange()) {
      // exteranl API call or more preprocessing...
    }

    for (let propName in changes) {
      let change = changes[propName];
      console.dir(change);
      if(change.isFirstChange()) {
        console.log(`first change: ${propName}`);
      } else {
        console.log(`prev: ${change.previousValue}, cur: ${change.currentValue}`);
      }
    }
  }
}

父组件

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <my-child [test]='parentTest'></my-child>
      <button (click)='onClick()'>Change Value</button>
    </div>
  `,
})
export class App {
  parentTest: string;
  name: string;
  counter = 1;

  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

  onClick() {
    this.parentTest = `test: ${this.counter}`;
    this.counter++;
  }
}

要在模板组件中捕获来自模板的更改,请改用 setter:

  // To catch changes from the template
  _test: string;
  get test(): string {
    return this._test;
  }

  @Input()
  set test(value: string) {
    this._test = value;
    console.log("Textbox value changed: " + this._test);
  }

或者您可以使用 Sajeetharan 的建议来捕捉模板在其关联模板中的更改。它也将起作用。

于 2018-02-07T00:34:38.157 回答
5

您在这里需要的是 ngModelChange 而不是 ngOnChanges

<input type="text" placeholder="Test field" (ngModelChange)="printVal()">

接着

printVal(){
  //detect model change here
}

ngOnChanges在@input 事件发射器上工作

于 2018-02-07T00:38:23.980 回答