0

I need to get the width of a css class in my angular component at the run time

<div class="document-section"></div>

I can't seems to get it by trying any of these:

$('.document-section').width()
$('.document-section').attr('width')

with error

Uncaught TypeError: $(...).width is not a function at :1:22

Can anyone help me with this? Thank you

6
  • try this code $('.document-section').css('width', '200px'); Commented May 18, 2017 at 6:04
  • What Angular version are you using? Commented May 18, 2017 at 6:08
  • Could be conflicts. stackoverflow.com/questions/28064784/… Commented May 18, 2017 at 6:08
  • I am not setting the width to use .css('width', '200px') even I tried $('.document-section').css('width') and same error as above Commented May 18, 2017 at 6:11
  • @Gezzasa angular 4 Commented May 18, 2017 at 6:11

1 Answer 1

1

To get the width of the class at runtime you need to first make sure it is drawn/rendered in the view.

So whatever your code to get the width should be included in the ngAfterViewInit() life cycle hook.

You dont specifically need to get it from css class just use ViewChild in the div and get it's width.

HTML

<div #documentSection class="document-section"></div>

TS

@ViewChild("documentSection")
private documentSection: ElementRef;

private divWidth: number;

public ngAfterViewInit(): void {
   this.divWidth = this.documentSection.nativeElement.offsetWidth;
}
Sign up to request clarification or add additional context in comments.

2 Comments

can you help me more with the ViewChild in the div?
Added a small example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.