2017-08-29 103 views
0

我有一個包含幾個textareas的頁面。每個textarea /複選框組合都在一個子組件中。如何在頁面加載時調整Angular2中textarea的大小

<input type="checkbox" [(ngModel)]="cb_value" [disabled]="cb_disabled" (click)="cbClicked($event)" name="cb"/> 
<textarea [myResizeTextarea]="newText" rows="2" spellcheck="true" class="form-control" [ngModel]="textValue" (ngModelChange)="valueChange($event)" name="textarea" [readOnly]="cb_value" (keypress)="cb_disabled=true;"></textarea> 

模型「textValue」從服務器中檢索並從父組件傳遞。

指令「myResizeTextarea」當前用於更改textarea,但inital textValue不調整大小。

我已經爲AfterViewInit,AfterViewChecked,AfterContentInit,AfterContentChecked和OnInit添加了處理程序。在他們中,我輸出scrollHeight到控制檯只是爲了檢查,他們都是textarea的默認高度。

如何根據初始內容調整高度?

這裏的指令:

export class ResizeTextareaDirective implements OnInit, AfterContentChecked, AfterViewInit, OnInit, OnChanges { 

    @Input() myResizeTextarea: string; 

    constructor(private el: ElementRef, private _renderer: Renderer, private changeDetectorRef: ChangeDetectorRef) { 

    this.el.nativeElement.style.overflow = 'hidden'; 
    this.el.nativeElement.style.resize = 'none'; 
    } 

    @HostListener('input') onInput() { 
    this.resize(); 
    } 
    @HostListener('transitionend') onTransEnd() { 
    const scrollHeight = this.el.nativeElement.scrollHeight + 'px'; 
    console.log('transend scrollheight=' + scrollHeight); 
    } 
    @HostListener('blur') onChange() { 
    const scrollHeight = this.el.nativeElement.scrollHeight + 'px'; 
    console.log('change scrollheight=' + scrollHeight); 
    } 

    resize() { 
    const scrollHeight = this.el.nativeElement.scrollHeight + 'px'; 
    console.log('scrollheight=' + scrollHeight); 
    this.el.nativeElement.style.height = 'auto'; 
    this.el.nativeElement.style.height = scrollHeight; 
    } 
} 

提前感謝!

回答

0

嘗試的console.log()'從你的指令荷蘭國際集團

this.el.nativeElement.style 

加載時(無論是從ngOnInit或ngAfterViewInit)。我敢打賭,除了在構造函數中分配的調整大小和溢出值之外,您會發現它完全空白。我不認爲Angular會默認讀取ElementRef的元素的所有樣式,只有那些被修改的元素。如果你這樣做

window.getComputedStyle(this.el.nativeElement) 

然後,你可能會看到所有相關的樣式實際上填充。雖然這種閱讀風格的方法是一個真正的性能殺手,所以我通常會找到一些方法來計算我在父級需要的初始樣式值,並將其作爲輸入傳遞並通過HostBinding綁定到它。

+1

感謝您的回答,因爲我是新人,所以我無法開心。看到我的帖子下面我是如何解決它。 –

1

謝謝你回答透輝石。我登錄了高度,但不是風格。我結束了這種略帶modifiying指令:

initResize = false; 
    initialScrollHeight: number; 

    ngAfterContentChecked(): void { 
    if (!this.initResize) { 
     const scrollHeight = this.el.nativeElement.scrollHeight; 
     if (scrollHeight !== this.initialScrollHeight) { 
     this.resize(); 
     this.initResize = true; 
     } 
    } 
    } 

第二次通過contentChecked事件顯示正確的scrollHeight屬性,所以我砍死這使它工作。不理想,我當然想知道做到這一點的正確方法,但它的工作原理並且足夠好。我會幫你解決問題的答案!

+0

無論什麼作品!布爾值不應該成爲一個問題,防止它被稱爲一百萬次。哦,這裏有一個提示,角度文檔不會很清楚 - 你可以使用@HostBinding直接綁定到DOM屬性,如scrollHeight和clientHeight。你只需要放棄'style'或'attr'前綴。 - > @HostBinding('scrollHeight')myScrHeight:number = 12345; – diopside

相關問題