问题描述
说明::在Angular 2中,在我的聊天屏幕上,我想在输入时增加聊天屏幕的大小,最多5行,然后显示滚动条.我该怎么办?
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?
问题:行为异常.滚动条在此处需要限制为5行,理想情况下会收缩,展开而无法正常工作.
Problem: Not behaving as expected. Scrollbar limit to 5 lines needs here, ideally contract, expand not working.
要求:它应在我按退格键时展开并收缩. 5行之后,它应该显示滚动条.
Requirement: It should expand as I type and contract as I press backspace. After 5 lines it should show scrollbar.
我的代码:
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>
推荐答案
您可以尝试创建类似以下的指令:
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';
}
}
}
然后在您的html中,您只需在代码中使用autosize属性,如下所示:
Then in your html you just use the autosize property in the tag like so:
<textarea autosize .....>
您还必须将指令添加到app.module中.希望这能解决您的问题.
You would have to add your directive to app.module as well.Hope this solves your problem.
这篇关于自动调整textarea的大小(最多5行),然后显示滚动条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!