Reputation: 671
I subscribed to valueChanges event to Angular's reactive form. I need to react on user inputs to prevent or correct his inputs, I tried few approaches but no one works as expected. While subscribing I get an Maximum call stack size exceeded
error.
const controlArray = <FormArray> this.formArray.get('items');
this.formArray.get('items').valueChanges.subscribe(val => {
val.forEach(s => {
controlArray.controls.forEach(control => {
const con = control.get('symbol');
if (con.value === s.symbol) {
con.setValue(s.symbol.toUpperCase());
}
});
});
});
In this case I just want change each letter input to uppercase. How can I do that? Or maybe there is simpler way than few iterates on each keyboard event?
I also tried put (change)="function(value)"
but it's called only when I use enter
on keyboard :/
Upvotes: 1
Views: 289
Reputation: 143
Maximum call stack size exceeded it's because you find yourself into an infinite loop, while watching you change a value than the watcher it's called again and it changes the value and the watcher is called again and it changes the value and again, and again, and again..
What you can do is to not emit the event inside your observer thanks to the native patchValue method:
this.myCustomForm.patchValue({
fieldSimbol: this.myCustomForm.value.fieldSimbol.toUpperCase()
}, { emitEvent: false })
Then you can include it in a generic buildForm function
buildForm() {
//...FormControls
this.myForm= new FormGroup({
fieldSimbol: new FormControl('', Validators.required)
});
//..ValidationMessages
this.validationMessages = {
'fieldSimbol': [
{ type: 'required', message: 'Please fill this field' }
]
}
//..observe value change
this.myForm.valueChanges.subscribe((data) => {
//..other stuff
//..some controls
//..what you probably need
this.myCustomForm.patchValue({
fieldSimbol: this.myCustomForm.value.fieldSimbol.toUpperCase()
}, { emitEvent: false })
});
}
Upvotes: 1
Reputation:
There is an easier way to achieve this. Use the input
directive. Let's assume you have an object book
and you want to set its field title
to upper case while the user enters a text.
HTML-Template
<input id="book-title" name="book-title" (input)="book.title = book.title.toUpperCase();"/>
Upvotes: 1