2016-12-06 7 views
1

Я пытаюсь использовать компонент в ngFor из этого SO Question, но я получаю сообщение об ошибке (выражение было изменено после его проверки. Предыдущее значение: '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

извините: - /. , ... , –