Angular 2 – Sanitizer & Debounce

Today quickly about two topics I had to resolve recently.

Bypassing Angular Sanitizer

First one is about Angular Sanitizer, or maybe DomSanitizer that is actually the class implementing the Sanitizer interface.

The purpose is quite clear, it is inspecting the content of a given value and prevents from unsafe content.

I have recently tested the oEmbed content for one of the vimeo videos (you can check what oEmbed is, in this post of mine) and I decided to bind a div innerHtml to some string representation of Html that is embedding the video on a website. So normally, I added to my div binding to the html like:

[innerHtml]="preview?.html"

But the video just wasn’t displayed and in the console you could see this:

WARNING: sanitizing HTML stripped some content

So I needed to turn this sanitation off, somehow.

I came across a neat approach to this topic using angular pipes (which I talked about also already >here<). The idea is that you simply apply the pipe to the content for which you want to bypass this Sanitizer stripping out your content.

The pipe implementation along with a reference to the source in the gist here:

Then, the div works fine with such a small modification:

[innerHtml]="preview?.html | safe: 'html'"

Debounce in Angular Forms

When you create a website form, you might want to react on the input and run some validation, or execute additional action. But how to recognize that the user has already finished typing?

In my case, I wanted to display the embedded content of video when user provides a valid url, but also avoid having to check the url with each letter typed in.

In angularjs (or Angular 1 if you like) you could simply add an option like:

ng-model-options="{ debounce: 1000 }"

In Angular 2 (or 4, or simply Angular) you can’t do this, so I needed to find another way. RxJS Observables to the rescue, modified my component a bit:


ngOnInit() {

this.videoUrl
.debounceTime(1000)
.distinctUntilChanged()
.subscribe(url => this.previewVideo(url));

}

I think the code describes itself quite well. debounceTime sets how long it waits before recreating observable, distinctUntilChanged only updates when the content has really changed.

Simple as that. Maybe you’ll find it useful.

Stay tuned.

 

 

One thought on “Angular 2 – Sanitizer & Debounce

  1. Pingback: dotnetomaniak.pl

Leave a Reply

Your email address will not be published. Required fields are marked *