[英]angular2 dynamic html insertion using directive
我試圖使用組件插入html,我需要綁定新創建的HTML元素。 以下是我的代碼段。
每當用戶嘗試向textarea輸入文本時,textarea應該在沒有任何滾動條的情況下增長,當焦點輸出時,它必須縮小到給定的高度或初始高度以及showmore按鈕。 點擊showmore按鈕調用showFull函數。
import {HostListener, Directive } from "@angular/core";
@Directive({
selector: 'textarea[autoGrow]',
})
export class AutoGrowDirective {
@HostListener('input', ['$event.target'])
onInput(inputElement: HTMLTextAreaElement): void {
this.growHeight(inputElement);
}
@HostListener('focusout', ['$event.target'])
onFocusout(inputElement: HTMLTextAreaElement): void {
this.shrinkHeight(inputElement);
}
@HostListener('focus', ['$event.target'])
onFocus(inputElement: HTMLTextAreaElement): void {
this.showFull(inputElement);
}
private initialHeight: number = 0;
public growHeight(textArea:HTMLTextAreaElement): void {
textArea.style.overflow = "hidden";
this.setInitialHeight(textArea.offsetHeight);
if(textArea.value.trim() == ""){
textArea.style.height = "100px";
} else if(textArea.scrollHeight > textArea.offsetHeight){
textArea.style.height = (textArea.scrollHeight+10) + "px";
}
}
public shrinkHeight(textArea:HTMLTextAreaElement): void {
if(textArea.scrollHeight > this.initialHeight){
let button: HTMLElement = document.createElement('button'); //, {id: 'textareaHeightChange', class: 'btn', type:""}
button.id = 'textareaHeightChange';
button.className = 'btn';
button.textContent = 'Show More';
// button.onclick = this.showFull2(); // on click invoke a function
console.info(button);
textArea.insertAdjacentElement('afterend',button); // insert this button only once
// <button id="textareaHeightChange" class="btn" type="">Show More</button>
}
textArea.style.height = this.initialHeight + "px";
textArea.style.overflow = "hidden";
}
public showFull(textArea:HTMLTextAreaElement): void {
textArea.style.height = textArea.scrollHeight + "px";
}
private setInitialHeight(height:number):void {
if(this.initialHeight == 0)
this.initialHeight = height;
}
private getInitialHeight(): number{
if(this.initialHeight != 0)
return this.initialHeight;
}
請有人給我一些燈。 我被困在最近兩天。
使用class和directive創建一個帶有css的類.auto-grow來增長你的文本區域,下面的指令將在焦點上添加這個類,並在刪除焦點或模糊時刪除該類。
import { Directive, ElementRef, HostListener, Input, Renderer } from '@angular/core';
@Directive({
selector: '[autoGrow]',
})
export class AutoGrowDirective {
private el: ElementRef;
constructor(private _el: ElementRef, public renderer: Renderer) {
this.el = this._el;
}
@HostListener('focus', ['$event']) onFocus(e) {
this.renderer.setElementClass(this._el.nativeElement, 'auto-grow', true);
return;
}
@HostListener('blur', ['$event']) onblur(e) {
this.renderer.setElementClass(this._el.nativeElement, 'auto-grow', false);
return;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.