Reputation: 453
I have textarea. I try to restrict width of value to 10 symbols. I am trying to cut value on input
event.
<textarea [(ngModel)]="smsMessage" (input)="changeSMSMessage()"></textarea>
changeSMSMessage() {
this.smsMessage = this.smsMessage.substr(0, 10);
console.log(this.smsMessage);
}
But it doesn't work. I see that value was cut in changeSMSMessage()
method, but on UI I see not changed value.
Plunker
When I changed event from input
to keyup
, it starts work properly. All characters after the tenth are deleted.
So, could someone explain why is input
event doesn't update value in textarea
?
Upvotes: 2
Views: 24152
Reputation: 638
Use formControl and subscribe to it's valueChanges when your component is initialized, which will allow you to use rxjs operators for advanced requirements like performing http requests, apply a debounce until user finish writing a sentence, take last value and omit previous.
import {Component, OnInit} from '@angular/core';
import { FormControl } from '@angular/forms';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
@Component({
selector: 'some-selector',
template: `
<input type="text" [formControl]="searchControl" placeholder="search">
`
})
export class SomeComponent implements OnInit {
private searchControl: FormControl;
private debounce: number = 400;
ngOnInit() {
this.searchControl = new FormControl('');
this.searchControl.valueChanges
.pipe(debounceTime(this.debounce), distinctUntilChanged())
.subscribe(query => {
console.log(query);
});
}
}
Upvotes: 0
Reputation:
You have several options :
1 - use the maxlength="10"
tag of the text area :
<textarea [(ngModel)]="smsMessage" maxlength="10"></textarea>
2 - Use a reactive form control with a built-in validator :
3 - Control the input :
<textarea [(ngModel)]="smsMessage" (change)="changeSMSMessage()"></textarea>
// TS
changeSMSMessage() {
this.smsMessage = this.smsMessage.length > 10 ? this.smsMessage.substr(0, 10), this.smsMessage;
}
Upvotes: 5