Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Angular 安全管道 #97

Open
deepthan opened this issue Sep 10, 2020 · 0 comments
Open

Angular 安全管道 #97

deepthan opened this issue Sep 10, 2020 · 0 comments
Labels

Comments

@deepthan
Copy link
Owner

Angular 安全管道使用方法

管道写法

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeResourceUrl, SafeScript, SafeStyle, SafeUrl } from '@angular/platform-browser';

@Pipe({
  name: 'safe',
})
export class SafePipe implements PipeTransform {
  constructor(protected sanitizer: DomSanitizer) {}

  public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
    switch (type) {
      case 'html':
        return this.sanitizer.bypassSecurityTrustHtml(value);
      case 'style':
        return this.sanitizer.bypassSecurityTrustStyle(value);
      case 'script':
        return this.sanitizer.bypassSecurityTrustScript(value);
      case 'url':
        return this.sanitizer.bypassSecurityTrustUrl(value);
      case 'resourceUrl':
        return this.sanitizer.bypassSecurityTrustResourceUrl(value);
      default:
        throw new Error(`Invalid safe type specified: ${type}`);
    }
  }
}

管道用法

 <span [outerHTML]="data | safe: 'html'"></span>

js使用safeStyle

import { DomSanitizer, SafeStyle } from '@angular/platform-browser';

export class xxx {
    img = "http://www.baidu.com/iamges/01";
    imgTransform: SafeStyle
    
    constructor(private sanitizer: DomSanitizer) {
     this.imgTransform = this.transformSafeStyle(this.img);
    }
    
    transformSafeStyle(url) {
        return this.sanitizer.bypassSecurityTrustStyle('url(' + url + ')');
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant