[英]Using Component in ngFor causes Error
我正在嘗試從此SO問題中使用ngFor中的組件,但出現錯誤(檢查后表達式已更改。上一個值:“未定義”。當前值:“假”。)。
該錯誤將引發onAfterViewInit函數。 有沒有更好的方法來初始化變量?
export class ReadMoreComponent implements AfterViewInit {
/**
* the text that need to be put in the container
*/
@Input()
public text: string;
/**
* maximum height of the container in [em]
*/
@Input()
public maxHeight: number = 4;
/**
* set these to false to get the height of the expanded container
*/
protected isCollapsed: boolean;
protected isCollapsable: boolean;
constructor(private elementRef: ElementRef) {
}
public ngAfterViewInit() {
this.doWork();
}
protected onResize(event) {
this.doWork();
}
/**
* collapsable only if the contents make container exceed the max height
*/
private doWork() {
if (this.calculateContainerHeight() > this.maxHeight) {
this.isCollapsed = true;
this.isCollapsable = true;
}
else {
this.isCollapsed = false;
this.isCollapsable = false;
}
}
/**
* Calculate height of content container.
*/
private calculateContainerHeight(): number {
let container = this.elementRef.nativeElement.getElementsByTagName('div')[0];
let lineHeight = parseFloat($(container).css("line-height"));
let currentHeight = Math.ceil(container.offsetHeight / lineHeight);
return currentHeight;
}
}
這是一個示例Plunk 。
ngAfterViewInit()
由更改檢測調用,並且當更改檢測導致模型更改時,您會收到此錯誤消息。 調用更改檢測可顯式修復錯誤:
constructor(private elementRef: ElementRef, private cdRef:ChangeDetectorRef) {}
public ngAfterViewInit() {
this.doWork();
this.cdRef.detectChanges();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.