当对div进行清理时,如何仅保留其中的
id
部分,并删除脚本部分。
import { OnInit, Component, Input, SecurityContext } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
selector: 'hello',
template: `{{unsafe}}
<br/>
<br/>
<div [innerHtml]="unsafe">
</div>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent implements OnInit {
@Input() name: string;
constructor(private sanitizer: DomSanitizer){}
output = 'heyo <div class="someclass" id="someid">sbang</div> <script>alert("bang");</script>';
unsafe = this.output;
ngOnInit(){
console.log(this.sanitizer.sanitize(SecurityContext.NONE, this.unsafe));
// heyo <div class="someclass" id="someid">sbang</div> <script>alert("bang");</script>
console.log(this.sanitizer.sanitize(SecurityContext.HTML, this.unsafe));
// heyo <div class="someclass">sbang</div>
console.log(this.sanitizer.sanitize(SecurityContext.STYLE, this.unsafe));
// unsafe
console.log(this.sanitizer.sanitize(SecurityContext.URL, this.unsafe));
// heyo <div class="someclass" id="someid">sbang</div> <script>alert("bang");</script>
console.log(this.sanitizer.sanitize(SecurityContext.RESOURCE_URL,this.unsafe));
// error
}
}