I'm new to Angular. I'm trying few simple things. I've an Input field. I just want to detect changes. I want to call some code whenever I type into the field. I checked these articles:
- Documentaion: Angular - onChanges
- What is the difference between OnChanges and DoCheck in Angular 2?
- Documentaion: Angular - Lifecycle hooks
- Stackoverflow: In Angular 4 the hook ngOnChanges is not firing on input
Here's my code:
my-component.component.html
<input [(ngModel)]="text">
my-component.component.ts
import { Component, OnInit, DoCheck } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnInit, DoCheck {
text="hello world";
constructor() { }
ngOnInit() {
}
ngOnChanges(changes: SimpleChanges) {
// changes.prop contains the old and the new value...
}
// ngDoCheck() { // TRIED THIS ALSO
// console.log("Changes detected")
// }
}
Two important information:
I tried
DoCheckalso, but this is not what I want. I want to see if only input field's value is changed or not. ButngDoCheckwill be called after every slight change in the rest of the components also as it is usingzone.js( i read this somewhere).I can't use
(keydown)also as I want to implement validation code later. I want validation to happen as I type-in. But with keydown, i noticed that I've to trigger validation code with some key-press even after the entered value is valid, let's say a Date/Time.
Keeping above two points in mind, please correct me. Here's the stackblitz.