Cập nhật v8
Dưới đây câu trả lời hoạt động nhưng làm cho ứng dụng của bạn gặp rủi ro bảo mật XSS! . Thay vì sử dụng this.sanitizer.bypassSecurityTrustResourceUrl(url)
, nên sử dụngthis.sanitizer.sanitize(SecurityContext.URL, url)
Cập nhật
Đối với phiên bản RC.6 ^, hãy sử dụng DomSanitizer
Plunker
Và một lựa chọn tốt là sử dụng đường ống tinh khiết cho điều đó:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer} from '@angular/platform-browser';
@Pipe({ name: 'safe' })
export class SafePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {}
transform(url) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}
nhớ thêm cái mới của bạn SafePipe
vào declarations
mảng AppModule. ( như đã thấy trên tài liệu )
@NgModule({
declarations : [
...
SafePipe
],
})
html
<iframe width="100%" height="300" [src]="url | safe"></iframe>
Plunker
Nếu bạn sử dụng embed
thẻ, điều này có thể thú vị đối với bạn:
Phiên bản cũ RC.5
Bạn có thể tận dụng DomSanitizationService
như thế này:
export class YourComponent {
url: SafeResourceUrl;
constructor(sanitizer: DomSanitizationService) {
this.url = sanitizer.bypassSecurityTrustResourceUrl('your url');
}
}
Và sau đó liên kết url
trong mẫu của bạn:
<iframe width="100%" height="300" [src]="url"></iframe>
Đừng quên thêm các mục nhập sau:
import { SafeResourceUrl, DomSanitizationService } from '@angular/platform-browser';
Mẫu Plunker