我有一個包含幾個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;
}
}
提前感謝!
感謝您的回答,因爲我是新人,所以我無法開心。看到我的帖子下面我是如何解決它。 –