Angular Dynamic Background Images

Angular dynamic background images

Use instead

<div [ngStyle]="{background: 'url(/img/' + item.img + ')', width: '200px', height: '150px'"></div>

or

<div [style.background]="'url(/img/' + item.img + ')'"
[style.width.px]="200" [style.height.px]="150p"></div>

See also In RC.1 some styles can't be added using binding syntax

Angular dynamic background image in div

if you want use dynamically. Dont use this syntactic

<div class="thumb" style="background-image: url('https://www.abcd.com/+ post.image)"></div> 

try do this

<div class="thumb" [ngStyle]="{'background-image': 'url(' + post.imageURL + ')'}" > <div>

Hope this will be helpful.

Angular style: add dynamically a background-image with an overlay

Follow on from my comment: Calling functions from the template will cause the change detector to loop through the function dozens of times - use ngOnInit or ngAfterViewInit and set a public property on the component instead, and then bind to that

Use the following ngStyle approach in the template to avoid the url sanitization problems without the hassle

[ngStyle]="{
'background-image': (chosenImage) ? 'url(' + chosenImage + ')' : ''
}"

How to set background-image URL dynamically when using *ngfor

as @ninecraft suggested in his comment .. this answer gave me the solution

[style.background-image]="'url('+for.item_image_1+')'" worked but it didn't resize the image that is why i thought it wasnt working,, i needed to use [style.background-size]="'100% 350px'" to resize the image and it worked perfectly.

(Angular 8) Validade image src for a dynamic background-image

With images you have access to events like onload an onError. You can utilize these two for your purpose. At the end I have presented a StackBlitz, but be sure when you test it, Stackblitz only work with https urls.

So when the user inputs something in the input you call a function, yes? That function could then look like:

changeBackground() {
let img = new Image();
// imgUrl is the property containing what user has typed in input
img.src = this.imgUrl;
img.onload = () => {
this.coverImage = img.src;
}
img.onerror = () => {
console.log('failed')
}
}

StackBlitz



Related Topics



Leave a reply



Submit