ionic3實現這個需要自定義指令,ionic4官網有個屬性(點我直達ionic4官網API),直接使用即可,如圖:
今天主要記錄下ionic3我是怎么實現ion-textarea高度自適應的。
1.創建指令
ionic g directive Autoresize_textarea
2.編輯指令
import { Directive, HostListener, ElementRef } from "@angular/core"; /** * 控制ion-textarea高度自適應的指令,在需要使用該指令的路由中添加這個指令,並在 * <ion-textarea>中使用, * 如:<ion-textarea autoresize></ion-textarea> * @author ywy * @date 2020-06-30 */ @Directive({ selector: "ion-textarea[autoresize]" // Attribute selector }) export class AutoresizeTextareaDirective { @HostListener('input', ['$event.target']) onInput(textArea: HTMLTextAreaElement): void { this.adjustHeight(); } constructor(public element: ElementRef) { } ngOnInit(): void { this.adjustHeight(); } adjustHeight(): void { let node = this.element.nativeElement.querySelector("textarea"); if (node) { node.style.height = node.scrollHeight + "px"; } } }
3.在需要使用該指令的頁面路由中添加並聲明此指令,如圖:
4.在html的ion-textarea中添加指令autoresize
<ion-textarea placeholder="請輸入" [(ngModel)]="content" autoresize></ion-textarea>
到這里,我們已經實現了ion-textarea的高度根據內容自適應的功能,但是還存在一個問題,就是回顯的時候並沒有自適應。這里我通過在ts觸發自適應代碼解決。
1.在使用該指令的ts中引入ElementRef
import { Component, ElementRef } from '@angular/core';
2.在構造方法中聲明
constructor(
public element: ElementRef
) { }
3.利用ionic的生命周期
ionViewDidEnter() { setTimeout(() => { this.textareaAutoHeight(); }, 1000); } textareaAutoHeight(){ let nodeList = this.element.nativeElement.querySelectorAll("textarea"); if (nodeList.length > 0) { nodeList.forEach(element => { if (element) { element.style.height = element.scrollHeight + "px"; } }); } }
如此回顯也會自適應了,完結~撒花~❀