można zdezynfekować HTML następująco:
import { Component, SecurityContext } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
selector: 'my-app',
template: `
<div [innerHTML]="_htmlProperty"></div>
`
})
export class AppComponent {
_htmlProperty: string = 'AAA<input type="text" name="name">BBB';
constructor(private _sanitizer: DomSanitizer){ }
public get htmlProperty() : SafeHtml {
return this._sanitizer.sanitize(SecurityContext.HTML, this._htmlProperty);
}
}
Demo plunker here.
Z Twoich komentarzach, rzeczywiście chcesz ucieczce nie odkażenie.
W tym celu: check this plunker, where we have both escaping and sanitization.
import { Component, SecurityContext } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
selector: 'my-app',
template: `Original, using interpolation (double curly braces):<b>
<div>{{ _originalHtmlProperty }}</div>
</b><hr>Sanitized, used as innerHTML:<b>
<div [innerHTML]="sanitizedHtmlProperty"></div>
</b><hr>Escaped, used as innerHTML:<b>
<div [innerHTML]="escapedHtmlProperty"></div>
</b><hr>Escaped AND sanitized used as innerHTML:<b>
<div [innerHTML]="escapedAndSanitizedHtmlProperty"></div>
</b>`
})
export class AppComponent {
_originalHtmlProperty: string = 'AAA<input type="text" name="name">BBB';
constructor(private _sanitizer: DomSanitizer){ }
public get sanitizedHtmlProperty() : SafeHtml {
return this._sanitizer.sanitize(SecurityContext.HTML, this._originalHtmlProperty);
}
public get escapedHtmlProperty() : string {
return this.escapeHtml(this._originalHtmlProperty);
}
public get escapedAndSanitizedHtmlProperty() : string {
return this._sanitizer.sanitize(SecurityContext.HTML, this.escapeHtml(this._originalHtmlProperty));
}
escapeHtml(unsafe) {
return unsafe.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")
.replace(/"/g, """).replace(/'/g, "'");
}
}
HTML escaping function użyte powyżej ucieka te same znaki jak angular code does (niestety, ich funkcja ucieczki nie jest publiczna, więc nie można go używać).
W przypadku zmiany kodu na następujące widać istnieje różnica. Chcę zachować tagi, ale ich nie oceniam. Czy wiesz, jak to zrobić?Szablon: '
{{}} _htmlProperty' (http://plnkr.co/edit/5vb1o2b9SX6F74U9g6F6?p=preview) – lfmunozWięc, co chcesz, to naprawdę nie zdezynfekować. To, czego chcesz, to ucieczka. - Będę edytować odpowiedź. – acdcjunior
Dodałem, uciekając. sprawdź odpowiedź. Jest nowy plunker. – acdcjunior