Jakob Svenningsson
Jakob Svenningsson

Reputation: 4305

Angular 2 - ElementRef.nativeElement.offSetwidth returning same value even when property has changed

I have a html element that looks like this:

   <h1 [style.font-size.em]="mysize" id="title-text" #titleText>{{ screenInfo.title }}</h1>

Where mysize is a variable that controls the font-size of the h1 tag. The h1 element's width is determined by the fontsize of the content.

I'm getting a reference to the h1 tag with

   @ViewChild('titleText') titleTextElement;

If i run the following code i get the following results

   console.log(this.titleTextElement.nativeElement.offsetWidth); 
    // returns 632px, which is the correct width.
   this.mysize *= 0.9;
   console.log(this.titleTextElement.nativeElement.offsetWidth); 
   //  returns 632px, but the new width is 572px.

Can anybody explain why this does not work? I would also appreciate if someone could show how I could get the updated offSetwidth value.

Upvotes: 1

Views: 6025

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657248

The view is only updated when change detection is run.

You can invoke change detection manually like:

   constructor(private cdRef:ChangeDetectorRef) {}
   ...

   console.log(this.titleTextElement.nativeElement.offsetWidth); 
    // returns 632px, which is the correct width.
   this.mysize *= 0.9;
   this.cdRef.detectChanges();
   console.log(this.titleTextElement.nativeElement.offsetWidth); 
   //  returns 632px, but the new width is 572px.

ant it should work as expected.

Upvotes: 5

Related Questions