本文介绍了在Angular 4中,钩子ngOnChanges不会在输入上触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Angular2/4相当陌生.我已经创建了带有输入字段的基本组件.用户输入将反映在绑定到用户输入的其他组件中.现在,我想为值更改设置一个通用的侦听器.

I am pretty new to Angular2/4. I have created a basic component with an input field. The user input will be reflected in the other components that are bound to the user input. Now I want to setup a general listener to a value change.

我认为OnChanges挂钩将是完美的解决方案,但从未调用ngOnChanges方法.我在做错什么吗?

I thought the OnChanges hook would be the perfect solution but ngOnChanges method was NEVER called. Am I doing something wrong?

任何提示表示赞赏...

Any hint appreciated...

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

@Component({
  selector: 'my-app',
  template: `
    <input [(ngModel)]="name">
    <input [(ngModel)]="name">
    <h1>{{name}}</h1>
  `,
})
export class AppComponent implements OnChanges {

  @Input() name: String = "abc"

  ngOnChanges(changes: SimpleChanges) {
    // changes.prop contains the old and the new value...
    console.log('on change', changes)
  }

}

每次内部更改组件属性时,都不会调用

推荐答案

ngOnChanges.当来自父组件的数据绑定将新值推入子组件时,它将被调用.因此,如果您的父组件具有

ngOnChanges is not called every time a component property changes internally. It gets called when the databinding from the parent component pushes a new value into the child component. So if your parent component has

<child-comp [name]="parentValue"></child-comp>

parentValue更改时,子组件的@Input() name将更改,并触发ngOnChanges

When parentValue changes, the child component's @Input() name will change and that will trigger ngOnChanges

查看文档:

要在表单输入发生更改时收到通知,从长远来看,最好的方法是学习反应型表单,因为它们使您可以在组件中创建FormControl对象,并公开一个非常简单的可观察对象,该对象在每次表单值更改时发出.

To be notified when your form inputs change, in the long run the best approach is to learn Reactive Forms because they make you create the FormControl objects in your component and expose a very simple observable that emits every time the form value changes.

如果您希望坚持使用模板驱动的表单,则可以绑定到输入的keypresskeyup事件,以触发要在更改上运行的任何逻辑.

If you wish to stick with template-driven forms, you can bind to the input's keypress or keyup event to fire whatever logic you want to run on change.

这篇关于在Angular 4中,钩子ngOnChanges不会在输入上触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 10:21