I'm currently working on an angular 5 application. I try to alter a member variable of my component in an input on the view and use the variable in my component after the change.
My structure is as follows:
Folder: my-test
1) my-test.component.html:
<input [(ngModel)]="hello" />
2) my-test.component.ts:
import { Component, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'my-test',
templateUrl: './my-test.component.html',
styleUrls: ['./my-test.component.css']
})
export class MyTestComponent implements OnChanges {
hello: string = "bonjour";
constructor() { }
ngOnChanges(changes: SimpleChanges) {
// I'd like to log the changes of my field 'hello',
// once it get's changed in the input on the ui...
console.log(changes);
}
}
Unfortunately this solution doesn't work. Do you know how to change an component's variable on the ui and use it in the component afterwards?
Thank you!!
you can use the (ngModelChange) directive
<input [(ngModel)]="hello" (ngModelChange)="myFunction()"/>
code:
import { Component } from '@angular/core';
@Component({
selector: 'my-test',
templateUrl: './my-test.component.html',
styleUrls: ['./my-test.component.css']
})
export class MyTestComponent {
hello: string = "bonjour";
constructor() { }
myFunction() {
console.log(this.hello);
}
}
You can use (ngModelChange)=functionToCall($event)
to call the function on model change and get updated value. It's pretty useful, and you can use it with regular [(ngModel)]
on the same element. In this case you can use just [ngModel]
instead of regular [(ngModel)]
and set new value to variable from functionToCall
function, but it depends on your needs. Here is a small demo (check the console to see updated values):
https://stackblitz.com/edit/angular4-rnvmhm?file=app%2Fapp.component.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With