I’ve got markup in a template where I bind a value to the style
attribute of a <button>
element:
<ion-col width-33 *ngFor="let post of row">
<button class="thumbnail" style="background-image: url({{post.thumbnail}})" (click)="onImageClick(post)"></button>
</ion-col>
But it appears that the style isn’t being set. When I examine the style of the element using Chrome’s dev tools there is no value for the style
attribute. However if I use I remove the variable binding the style shows up:
<ion-col width-33 *ngFor="let post of row">
<button class="thumbnail" style="background-image: url()" (click)="onImageClick(post)"></button>
</ion-col>
Did something change in Beta7 or is this a bug in Angular?
<ion-col width-33 *ngFor="let post of row">
<button class="thumbnail" [style]="background-image: url({{post.thumbnail}})" (click)="onImageClick(post)"></button>
</ion-col>
Almost, but that doesn’t quite work. I dug around and was able to find some Angular documentation that discusses that style
binding. It looks like I should be able to do [style.backgroundImage]="post.thumbnail"``, however the css needs to be "background-image: url(...)" and
[style.backgroundImage]=“url(post.thumbnai)l”`` results in an error along the lines of “url is not a function in the parent context”. The solution I’ve found just now is to do [ngStyle]="post.style"
where post.style
is an object along the lines of:
{
'background-image': `url(${post.thumbnail})`,
}
While that is somewhat less convenient than being able to use [style.backgroundImage]
directly, it at least get’s things working again for me.
I have a suspicion you might be running into security sanitization. See the discussion on this PR.
Huh, that does seem relevant, though I don’t 100% follow what’s going on. If I understand correctly what I’m doing (building a string with “url(…)” though code) is the suggested workaround for this security-related issue?
For now, I believe you’re right. What you were trying to do before might become legal later.