Colouracetam
Colouracetam

Reputation: 23

Angular image size problem in ckeditor content

I am using CKEditor in order to create Rich Text Fields which are stored in the database of my back-end. My problem is: when I add images to these fields via CKEditor, width and height attributes are set with CSS in a style tag, like this:

<img
  alt=""
  src="https://something.cloudfront.net/something.jpg" 
  style="height:402px; width:716px"
/>

And when I try to display the Rich Text Field containing the above code in angular like this:

<p class="card-text" [innerHTML]="blogEntry.content"></p>

Angular produces the following code without including the inline CSS which contains the height and width properties:

<img alt="" src="https://something.cloudfront.net/something.jpg">

This results in image being shown in original size regardless of height and width properties set using the CKEditor.

I don't want height and width properties to be discarded. What would be the ideal solution to this problem? I will be glad if you can help. Thanks.

Upvotes: 1

Views: 1080

Answers (1)

jahller
jahller

Reputation: 2963

You have to set the proper security context for the content you are injecting.

By default angular sanitizes everything that you inject into your HTML. But be aware that this is a potential security risk

See https://angular.io/guide/security for all information on angular's security settings.

See https://angular.io/guide/security#bypass-security-apis on how to bypass the security context.

And here an example function that you could use in your component:

constructor(private sanitizer: DomSanitizer) {}

public createTrustedHtml(blogContent: string) {
   return this.sanitizer.bypassSecurityTrustHtml(blogContent);
}

and in your template

<p class="card-text" [innerHTML]="createTrustedHtml(blogEntry.content)"></p>

Always be aware of the risk that comes with bypassing angular's default security context! Only use it, if you trust the content 100%. this can create potential security risks and open the doors for XSSI and CSRF/XSRF attacks.

Upvotes: 1

Related Questions