João Oliveira
João Oliveira

Reputation: 85

Force [innerHTML] content to fit inside div width

I amm using angular 7 and i am trying to render some html i get from an external DB (MySQL). I am using a div and rendering the html with [innerHTML] on this div. The problem is the rendered html exceeds the width of the div. The html can contain only text, but can also contain images, tables, and images inside tables.

After receiving the html from DB i run this function.

this.sanitizer.bypassSecurityTrustHtml(html);

I have already tried put word-wrap:break-word in the css but the problem remained.

For the purpose of testing i changed the string with html that comes from the DB to a simple img tag with a src to a image from the web and the image is rendered with its real size, also not fitting the div.

This is what i have right now.

<div class="bloghtml" [innerHTML]="post.html_post"></div>
.bloghtml {
  display: inline-flex;
  max-width: 1300px;
}

So i need to force the innerHTML to adjust (including resizing images) to fit in the div. Is there anyway to accomplish this?

Upvotes: 1

Views: 4767

Answers (2)

Rezwan
Rezwan

Reputation: 41

You can try using SafeHtml. It's like

<div class="bloghtml" [innerHTML]="post.html_post | safeHtml"></div>

To know more Using Angular innerHtml to display user-generated content without sacrificing security

Upvotes: 0

Azzam Asghar
Azzam Asghar

Reputation: 346

Angular puts the content of innerHtml in a shadow DOM so you won't be able to apply styles to it like that. There are some workarounds for this first is using ::ng-deep Which is deprecated as mentioned in the Angular docs which says

The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools

If you change your code slightly

Html

<div [innerHTML]="html_post"></div>

JS

html_post = '<div class="bloghtml"><img src="https://via.placeholder.com/150" /></div>'

CSS

:host ::ng-deep .bloghtml { 
  display: inline-flex;
  max-width: 100px;
  overflow-wrap: break-word;
  word-wrap: break-word;
}

:host ::ng-deep .bloghtml img { 
  max-width: 100px;
}

Now you can style it in any way you want. Here is a stack blitz demonstrating this in action.

Upvotes: 3

Related Questions