angular - 为什么不会调用 ngOnChanges 钩子(Hook)?

标签 angular typescript angular-components

我正在尝试通过实验学习 Angular 2,我发现 ngOnChanges 不会在以下代码中触发:

app.component.ts:

import { Component, Input } from "@angular/core"
import { FormsModule } from '@angular/forms';
import { OnChanges, SimpleChanges } from '@angular/core/src/metadata/lifecycle_hooks';
@Component({
  selector: 'my-app',
  template: `
    Enter text : <input type="text" [(ngModel)]='userText'  />
    <br/>
    Entered text :  {{userText}} 
  `
})

export class AppComponent {
  @Input()  userText: string;
  name: string = "Tom";

  ngOnChanges(changes: SimpleChanges): void {
    for (let propertyName in changes) {
      let change = changes[propertyName];
      let current = JSON.stringify(change.currentValue);
      let previouis = JSON.stringify(change.previousValue);
      console.log(propertyName + ' ' + current + ' ' + previouis);
    }

  }
}

上面的代码没有触发 ngOnChanges

但是,如果我创建一个“简单”的单独组件并在 app.scomponent.ts 中使用它,则以下工作:

app.component.ts:

import {Component} from "@angular/core"
import {FormsModule} from '@angular/forms'; 
@Component({
  selector: 'my-app',
  template: `
    Enter text : <input type="text" [(ngModel)]='userText' />
    <br/>
    <simple [simpleInput]='userText'></simple>
  `
})

export class AppComponent{
  userText:string;
  name:string ="Tom";


}

simple.component.ts:

import {Component,Input} from '@angular/core';
import { OnChanges,SimpleChanges } from '@angular/core/src/metadata/lifecycle_hooks';

@Component({
    selector:'simple',
    template: `You entered {{simpleInput}} `
})
export class SimpleComponent implements OnChanges{
    ngOnChanges(changes: SimpleChanges): void {
        for(let propertyName in changes){
            let change=changes[propertyName];
            let current=JSON.stringify(change.currentValue);
            let previouis=JSON.stringify(change.previousValue);
            console.log(propertyName+ ' '+current+ ' ' +previouis);
        }

    }
    @Input() simpleInput: string;

}

有人可以提供解释吗?我在这里做错了什么?

最佳答案

我认为您可能误解了@Input 字段的意图。 @Input 字段允许在父组件和子组件之间进行通信,组件内的数据绑定(bind)不需要它们。数据绑定(bind)不需要任何属性,字段只需要公开即可。 作为一个生命周期钩子(Hook),ngOnChanges 旨在对@Input 字段的变化使用react,而不是 html 输入元素。

如果你想要比双向数据绑定(bind)更精细的更改行为,请尝试

<input type="text" [(ngModel)]='userText' (ngModelChange)="onUserTextChange($event)">

(很抱歉,如果上面的代码不能开箱即用,我会在回到我的开发人员机器后立即测试并清理它)

您可以找到更多信息here .

关于angular - 为什么不会调用 ngOnChanges 钩子(Hook)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49716105/

相关文章:

angular - 如何在 Angular 解析器的管道中进行过滤?

angular - Rxjs 可观察的返回错误时抛出错误 错误被捕获并返回

angular - 在 Angular 2 应用程序中使用 Material 单选按钮的问题

angular - 显示注销页面时删除页眉和页脚

javascript - 如何在 Angular 按钮单击时设置边距?

typescript - tsconfig.json 中的模块属性

javascript - 在 typescript 中指定 keyof 类型

angular - 使用组件和服务创建模块

angular - 为什么 Angular 坚持为组件使用自定义前缀?

css - 如何删除 WebStorm sass-lint 错误 "Unknown pseudo selector ' ng-deep'”