ng-bind-html / $sce in modern Angular
ng-bind-html becomes a binding to [innerHTML], which sanitizes the content by default. $sce becomes DomSanitizer, used only when you need to bypass that sanitization.
Before · AngularJS
// controller
vm.body = $sce.trustAsHtml(article.bodyHtml);
vm.videoUrl = $sce.trustAsResourceUrl(article.videoUrl);
<!-- template -->
<div ng-bind-html="vm.body"></div>
<iframe ng-src="{{ vm.videoUrl }}"></iframe>After · Angularprivate sanitizer = inject(DomSanitizer);
article = input.required<Article>();
videoUrl = computed(() =>
this.sanitizer.bypassSecurityTrustResourceUrl(this.article().videoUrl));
<!-- template -->
<div [innerHTML]="article().bodyHtml"></div>
<iframe [src]="videoUrl()"></iframe>What changes
- [innerHTML] removes scripts and event handler attributes on its own; there is no ngSanitize module to install.
- $sce.trustAsHtml becomes bypassSecurityTrustHtml, for content you fully control.
- URLs for iframes and similar elements need bypassSecurityTrustResourceUrl, like trustAsResourceUrl before.
Migration tip. List every trustAs call during the assessment, because each one is a security decision someone made years ago. Many trustAsHtml calls can go away, since the default sanitization is enough for formatted text.
Related
Planning a migration or a micro-frontend platform?
In a 20-minute call you describe your situation and I tell you how I'd approach it. If it isn't worth doing yet, I'll say so.
Message me on LinkedIn