1

I am trying to use a component in ngFor from this SO Question but I get an Error (Expression has changed after it was checked. Previous value: 'undefined'. Current value: 'false'.).

The error is thrown in the onAfterViewInit function. Is there a better way to initialize the variables?

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;
}
}

Here is a example Plunk.

Community
  • 1
  • 1
Marko
  • 1,291
  • 1
  • 21
  • 37

1 Answers1

2

ngAfterViewInit() is called by change detection, and when change detection causes model changes, you get this error message. Calling change detection explicitly fixes the error:

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

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

Plunker example

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567