SoFunction
Updated on 2025-04-13

Div implements textarea with adaptive height to implement angular bidirectional binding

I believe many students have simulated Tencent’s QQ to create a chat application, at least I am one of them.

One of the problems I encountered during the process is that the QQ input box has adaptive height, and the maximum height is 3row.

If you plan to use textarea like me, then I'm sorry, you were wrong in the beginning.

Textarea is not impossible, and then I was wrong. (It is to listen to the scroll if it appears, increase the height of 1 rows) However, this is really frustrating

 ('change','keydown'){
 if(scrollTop > 0 ) {
  += 1
 }
}

The correct way to open should be to use the html5 global attribute. However, in the ios mobile terminal, using contenteditable alone cannot obtain focus and input, so you need to add the use-select attribute.

<div contenteditable='true' style='-webkit-use-select:text'></div>
//Different browsers,Support,It's a bit different from the implementation method,androidandiosdefaultwebkitKernel,So using this is enough

Use editable div in angular:—》 The ng-model directive of angular is only used for select, input, textarea, and is not applicable to div, so it needs to be further encapsulated

/*
 * Editable div
 * When there are expressions in comments, add img (expression) to the div
 * <div contenteditable strp-br='true' style='-webkit-use-select:text'></div>
 */
('contenteditable', function() {
 return {
 restrict: 'A', 
 require: '?ngModel', 
 link: function(scope, element, attrs, ngModel) {
 if (!ngModel) return; 
 ngModel.$render = function() {
 (ngModel.$viewValue || '');
 };
 ('blur keyup change', function() {
 scope.$evalAsync(read);
 });
 read(); // initialize
 function read() {
 var html = ();
 if (  &amp;&amp; html == '&lt;br&gt;' ) { //Clear <br>  html = '';
 }
 ngModel.$setViewValue(html);
 }
 }
 };
});

The above is all the content of this article. I hope that the content of this article will help you study or work. I also hope to support me more!