2016-12-06 41 views
1

我想在这个SO Question的ngFor中使用一个组件,但是我得到了一个错误(表达式在它被检查后发生了改变,前一个值:'undefined',当前值:'false'。) 。在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

回答

2

ngAfterViewInit()被更改检测调用,并且当更改检测导致模型更改时,您会收到此错误消息。 调用变化检测明确修正错误:

constructor(private elementRef: ElementRef, private cdRef:ChangeDetectorRef) {} 

public ngAfterViewInit() { 
    this.doWork(); 
    this.cdRef.detectChanges(); 
} 

Plunker example

+1

但我刚键入这个问题,以及:d – PierreDuc

+0

抱歉: - /。 。 ..。 。 –