Hi
How to show the remaining character when i type in text area.
Remaining character of 10/300 like this.
Thanks in advance.
Ramji
Hi
How to show the remaining character when i type in text area.
Remaining character of 10/300 like this.
Thanks in advance.
Ramji
Something like this would do the trick: https://stackblitz.com/edit/ionic-react-textarea-count?file=src/App.js
const MyTextarea = () => {
const [value, setValue] = useState("");
const [count, setCount] = useState(0);
const max = 20;
useEffect(() => {
setCount(value.length);
}, [value]);
return (
<>
<IonTextarea
style={{ border: "1px solid black" }}
value={value}
onIonInput={(e) => setValue(e.target.value)}
/>
{count} / {max}
</>
);
};
Hi,
Thanks for your help.
How to do in Ionic/Angular.
Thanks in advance
Regards,
Ramji
It’s a similar idea in Angular. Moving to the Angular category in case someone wants to jump in.
I would do something like so:
<ion-item>
<ion-label>comment</ion-label>
<ion-textarea [formControl]="comment"></ion-textarea>
</ion-item>
<div class="usage-stats">
{{charsUsed}} / {{charsAllowed}}
</div>
@UntilDestroy()
@Component({
selector: "app-root",
templateUrl: "app.component.html",
styleUrls: ["app.component.scss"]
})
export class AppComponent implements OnInit {
charsAllowed = 100;
charsUsed = 0;
comment = new FormControl("", Validators.maxLength(this.charsAllowed));
ngOnInit(): void {
this.comment.valueChanges.pipe(untilDestroyed(this))
.subscribe((nv: string) => this.charsUsed = nv.length);
}
}
The @UntilDestroy
decorator comes from ngneat/until-destroy, and manages that valueChanges
subscription so that it doesn’t leak. Obviously this could be done without reactive forms, but I like the way that this keeps as much logic as possible in the controller and out of the template.