AlbertMunichMar
AlbertMunichMar

Reputation: 1866

Angular style background image url + linear gradient

I want to put a picture in a div, while using a gradient. After some tries, my best solution is this one:

<div 
  class="form-edit-picture-wrapper"
  [style.background-image]="'linear-gradient(-225deg, rgba(0,0,0,0.6) 50%, rgba(0,36,61,0.6) 80%), url(/assets/hands.jpeg)'"
>

But still not working.

Any help?

Upvotes: 5

Views: 10472

Answers (5)

Dwiyi
Dwiyi

Reputation: 646

using @Nikhil Chandu answer, but using pipe.

make class pipe :

import { Pipe, PipeTransform } from "@angular/core";
import { DomSanitizer, SafeStyle } from '@angular/platform-browser';

@Pipe({
    name: 'sanitizeStyle'
})
export class SanitizeStylePipe implements PipeTransform {

    constructor(private _sanitizer:DomSanitizer) {
    }

    transform(v:string):SafeStyle {
        return this._sanitizer.bypassSecurityTrustStyle(v);
    }
}

using sanitizeStyle

<div  [style.background-image]="'linear-gradient(rgba(0, 0, 0, .3), rgba(0, 0, 0, .3)), url(../assets/image.png)' | sanitizeStyle">

Upvotes: 1

Nikhil Chandu
Nikhil Chandu

Reputation: 421

sanitize and it shall work:

in your .ts file:

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

in your export class add:

bgImage:any;

in your constructor add:

private sanitizer: DomSanitizer

then create an image url and sanitize:

this.bgImage = this.sanitizer.bypassSecurityTrustStyle('linear-gradient(-225deg, rgba(0,0,0,0.6) 50%, rgba(0,36,61,0.6) 80%),url(/assets/hands.jpeg)');

Thats the sanitizing part.

Now in your html:

<div [style.background-image]="bgImage">

There is also an other way to do this without sanitizing using ngStyle:

<div [ngStyle]="{'background-image': 'linear-gradient(-225deg, rgba(0,0,0,0.6) 50%, rgba(0,36,61,0.6) 80%),url(/assets/hands.jpeg)'}"></div>

hope that helps!

Upvotes: 0

k.s.
k.s.

Reputation: 3004

If you want to use it in the template you can use the [ngStyle] directive.

[ngStyle]="{background: 'linear-gradient(-225deg, rgba(0,0,0,0.6) 50%, rgba(0,36,61,0.6) 80%), url(/assets/hands.jpeg)'}"

Here's a quick example

Upvotes: 2

Domenik Reitzner
Domenik Reitzner

Reputation: 1613

Use plain css and not inline styles!

.form-edit-picture-wrapper{
    background: linear-gradient(-225deg, rgba(0,0,0,0.6) 50%, rgba(0,36,61,0.6) 80%),
    url(/assets/hands.jpeg)
}

You would also need to set height and width as there seems to be no content in the div you provided.

Upvotes: 2

dev-assassin
dev-assassin

Reputation: 271

you can do it like this:

<div class="image">
 <image src="url" alt="">
</div>

.css file:

.image {
  background: linear-gradient(-225deg, rgba(0,0,0,0.6) 50%, rgba(0,36,61,0.6) 80%);
  background: -webkit-linear-gradient(-225deg, rgba(0,0,0,0.6) 50%, rgba(0,36,61,0.6) 80%);
  background: -moz-linear-gradient(-225deg, rgba(0,0,0,0.6) 50%, rgba(0,36,61,0.6) 80%);
}

Upvotes: -2

Related Questions