问题
Explanation: In Angular 2, on my chat screen, I want to increase the size of my chat screen as I type, to max 5 lines and then show scrollbar. How do I do it?
Problem: Not behaving as expected. Scrollbar limit to 5 lines needs here, ideally contract, expand not working.
Requirement: It should expand as I type and contract as I press backspace. After 5 lines it should show scrollbar.
My code:
home.ts
autogrow(){
let textArea = document.getElementById("textarea")
textArea.style.overflow = 'hidden';
textArea.style.height = '0px';
textArea.style.height = textArea.scrollHeight + 'px';
}
home.html
<textarea id="textarea" (keyup)="autogrow()" ></textarea>
回答1:
You could try making a directive something like this:
@Directive({
selector: 'ion-textarea[autosize]'
})
export class AutoSizeDirective implements OnInit {
@HostListener('input', ['$event.target'])
onInput(target): void {
this.adjust(target);
}
@HostListener('focus', ['$event.target'])
onFocus(target): void {
this.adjust(target);
}
constructor(public element: ElementRef) {}
ngOnInit(): void {
setTimeout(() => this.adjust(), 100);
}
adjust(textArea: HTMLTextAreaElement = null): void {
if (textArea == null) {
textArea = this.element.nativeElement.getElementsByTagName('textarea')[0];
}
textArea.style.overflow = 'hidden';
textArea.style.height = 'auto';
textArea.rows = 1;
if (textArea.scrollHeight < 200) { //or whatever height you like
textArea.style.height = textArea.scrollHeight + 'px';
} else {
textArea.style.height = 200 + 'px';
}
}
}
Then in your html you just use the autosize property in the tag like so:
<textarea autosize .....>
You would have to add your directive to app.module as well. Hope this solves your problem.
来源:https://stackoverflow.com/questions/57970245/autosize-textarea-with-max-5-line-limit-then-show-scrollbar