Angular 2 アプリのコンポーネント テンプレートで DIV の背景画像を設定したいのですが、コンソールに次の警告が表示され続け、期待した効果が得られません... Angular2 のセキュリティ制限により動的 CSS 背景画像がブロックされているのか、HTML テンプレートが壊れているのかわかりません。
これはコンソールに表示される警告です(img の URL を次のように変更しました/img/path/is/correct.png
)。
警告: 安全でないスタイル値 url(SafeValue をサニタイズするには、[property]=binding: /img/path/is/correct.png を使用する必要があります (http://g.co/ng/security#xss)) (見るhttp://g.co/ng/security#xss)。
重要なのは、Angular2 を使用してテンプレートに挿入される内容をサニタイズすることですDomSanitizationService
。以下は、テンプレートにある HTML です。
<div>
<div>
<div class="header"
*ngIf="image"
[style.background-image]="'url(' + image + ')'">
</div>
<div class="zone">
<div>
<div>
<h1 [innerHTML]="header"></h1>
</div>
<div class="zone__content">
<p
*ngFor="let contentSegment of content"
[innerHTML]="contentSegment"></p>
</div>
</div>
</div>
</div>
</div>
コンポーネントは次のとおりです...
Import {
DomSanitizationService,
SafeHtml,
SafeUrl,
SafeStyle
} from '@angular/platform-browser';
@Component({
selector: 'example',
templateUrl: 'src/content/example.component.html'
})
export class CardComponent implements OnChanges {
public header:SafeHtml;
public content:SafeHtml[];
public image:SafeStyle;
public isActive:boolean;
public isExtended:boolean;
constructor(private sanitization:DomSanitizationService) {
}
ngOnChanges():void {
map(this.element, this);
function map(element:Card, instance:CardComponent):void {
if (element) {
instance.header = instance.sanitization.bypassSecurityTrustHtml(element.header);
instance.content = _.map(instance.element.content, (input:string):SafeHtml => {
return instance.sanitization.bypassSecurityTrustHtml(input);
});
if (element.image) {
/* Here is the problem... I have also used bypassSecurityTrustUrl */
instance.image = instance.sanitization.bypassSecurityTrustStyle(element.image);
} else {
instance.image = null;
}
}
}
}
}
たとえば、[src]="image" を使用してテンプレートにバインドしただけの場合、次の点に注意してください。
<div *ngIf="image">
<img [src]="image">
</div>
image
すべてを使用して合格しましたが、bypassSecurityTrustUrl
うまく機能しているようです...私が間違っているところを誰かわかりますか?
ベストアンサー1
url
ステートメント全体をbypassSecurityTrustStyle
:で囲む必要があります。
<div class="header" *ngIf="image" [style.background-image]="image"></div>
そして
this.image = this.sanitization.bypassSecurityTrustStyle(`url(${element.image})`);
それ以外の場合は有効なスタイルプロパティとして認識されません