首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么不叫ngOnChanges钩子?

为什么不叫ngOnChanges钩子?
EN

Stack Overflow用户
提问于 2018-04-08 08:48:42
回答 1查看 328关注 0票数 2

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

app.component.ts:

代码语言:javascript
复制
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.component.ts:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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;

}

有谁能解释一下吗?我在这里做错什么了?

EN

回答 1

Stack Overflow用户

发布于 2018-04-08 11:13:41

我认为您可能误解了“输入字段”的意图。@输入字段允许父组件和子组件之间进行通信,组件中的数据库不需要它们。数据库不需要任何属性,字段必须是公共的。作为一个生命周期钩子,ngOnChanges的目的是对@输入字段上的更改做出反应,而不是对html输入元素作出反应。

如果您想要比双向绑定更精细的更改行为,请尝试。

代码语言:javascript
复制
<input type="text" [(ngModel)]='userText' (ngModelChange)="onUserTextChange($event)">

(很抱歉,如果上面的代码不能正常工作,我一回到开发人员机器上就会立即测试和清理)

您可以找到更多的信息这里

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49716105

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档