I am trying the following lines to set the background image.but it not works. what are the way set background image in constantly in my application.
app.component.html
<div [ngStyle]="{'background' : 'url(./images/trls.jpg)'}">
<router-outlet></router-outlet>
<alert></alert>
</div>
You can use ngStyle to set background for a div
<div [ngStyle]="{background-image: 'url(./images/' + trls.img + ')'}"></div>
or you can also use built in background style:
<div [style.background-image]="'url(/images/' + trls.img + ')'"></div>
This works for me:
put this in your markup:
<div class="panel panel-default" [ngStyle]="{'background-image': getUrl()}">
then in component:
getUrl()
{
return "url('http://estringsoftware.com/wp-content/uploads/2017/07/estring-header-lowsat.jpg')";
}
Below answer worked for angular 4/5.
In app.component.css
.image{
height:40em; background-size:cover; width:auto;
background-image:url('copied image address');
background-position:50% 50%;
}
Also in app.component.html simply add as below
<div class="image">
Your content
</div>
This way I was able to set background image in Angular 4/5.
If you plan using background images a lot throughout your project you may find it useful to create a really simple custom pipe that will create the url for you.
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'asUrl'
})
export class BackgroundUrlPipe implements PipeTransform {
transform(value: string): string {
return `url(./images/${value})`
}
}
Then you can add background images without all the string concatenation.
<div [ngStyle]="{ background: trls.img | asUrl }"></div>
In Html
<div [style.background]="background"></div>
In Typescript
this.background=
this.sanitization.bypassSecurityTrustStyle(`url(${this.section.backgroundSrc}) no-repeat`);
A working solution.
What is the recommended way to dynamically set background image in Angular 4
this one is working for me also for internet explorer:
<div class="col imagebox" [ngStyle]="bkUrl"></div>
...
#Input() background = '571x450img';
bkUrl = {};
ngOnInit() {
this.bkUrl = this.getBkUrl();
}
getBkUrl() {
const styles = {
'background-image': 'url(src/assets/images/' + this.background + '.jpg)'
};
console.log(styles);
return styles;
}
I wanted a profile picture of size 96x96 with data from api. The following solution worked for me in project Angular 7.
.ts:
#Input() profile;
.html:
<span class="avatar" [ngStyle]="{'background-image': 'url('+ profile?.public_picture +')'}"></span>
.scss:
.avatar {
border-radius: 100%;
background-size: cover;
background-position: center center;
background-repeat: no-repeat;
width: 96px;
height: 96px;
}
Please note that if you write background instead of 'background-image' in [ngStyle], the styles you write (even in style of element) for other background properties like background-position/size, etc. won't work. Because you will already fix it's properties with background: 'url(+ property +) (no providers for size, position, etc. !)'. The [ngStyle] priority is higher than style of element. In background here, only url() property will work. Be sure to use 'background-image' instead of 'background'in case you want to write more properties to background image.
A very easy solution is to declare the image with a loading class and remove this class when image is loaded. You can then customize the placeholder in CSS, as it should be.
HTML :
<img class="persona-avatar loading" #avatar
(load)="avatar.classList.remove('loading'); "
src="/assets/img.png"
alt=""/>
SCSS :
.persona-avatar {
width: 50px;
height: 50px;
&.loading {
background-image: url("data:image/png;base64,iVBORw0K...");
background-size: contain;
}
}
It is better to use a base64 image to not have the same load problem with the placeholder.
This can be done with a custom directive, instead of having a method that will execute in a loop affecting performance.
In my case I would created a BackImgDirective like this:
import {Directive, ElementRef, Input, OnInit, Renderer2} from "#angular/core";
#Directive({ selector: '[appBackImg]'})
export class BackImgDirective implements OnInit {
#Input() appBackImg = ''
constructor(private el: ElementRef, private renderer: Renderer2) {}
ngOnInit() {
this.setBackImg()
}
setBackImg(){
this.renderer.setStyle(this.el.nativeElement, 'background-image', 'url(' + this.appBackImg + ')')
}
}
And use it like this:
<div [appBackImg]="slide.image"> </div>
Related
I'm using Angular 11 and https://www.npmjs.com/package/angular-responsive-carousel responsive carousel. The carousel is populated with mat-cards using an array. But when the page loads for the first time all the cards are rendered on top of each other as shown here
But it should look like this
But after the window is resized and taken back to the original size the carousel renders fine. I want to find a way to have the cards rendered right in the first go.
The HTML code looks like this
<carousel [dots]="true" [cellsToShow]=cellsToShow [height]="carouselHeight" [autoplay]="false"
[autoplayInterval]="2000"
[borderRadius]="2" [pauseOnHover]="true">
<div class="carousel-cell" *ngFor="let item of cards; index as i; trackBy: fun">
<mat-card class="example-card mat-elevation-z0">
<mat-card-header>
<a mat-card-avatar class="example-header-image" [href]="telegramUrl" target="_blank"</a>
<mat-card-title><b>Ultime Offerte</b></mat-card-title>
<mat-card-subtitle><i>Di Offerte Nerd</i></mat-card-subtitle>
</mat-card-header>
<br>
<div class="example-card-image"><img mat-card-image [src]=item[0] alt=""></div>
<mat-card-content>
<div [innerHTML]="item[1]"></div>
<br>
{{item[2]}} {{item[3]}}
</mat-card-content>
</mat-card>
</div>
The CSS looks like this.
.carousel{
position: relative;
z-index: 1;
padding-left: 10%;
padding-right: 10%;
}
.carousel-cells{
height: auto !important;
}
.carousel-cell{
height: auto !important;
}
.example-card {
max-width: 70vw;
text-align: left;
overflow-wrap: break-word;
height: auto !important;
border-style: solid;
border-width: thin;
}
It's just my guess but try to call cdRef.markForCheck() in ngAfterViewInit() lifecycle hook of the component where you use the carousel:
import { Component, AfterViewInit, ChangeDetectorRef } from '#angular/core';
#Component({
...
})
export class MyComponent implements AfterViewInit {
constructor(private cdRef: ChangeDetectorRef) {}
ngAfterViewInit(): void {
this.cdRef.markForCheck();
// also try this.cdRef.detectChanges(); instead of the above
}
}
But much better is to trigger change detection right at the point where the data which you feed to the carousel is ready.
It happens because the carousel renders before the data is added to the cards. Since there is no data during carousel rendering, carousel cells don't take the actual width inside the carousel.
There is a simple solution for this. We need to provide the default width for the carousel-cells. It can be done by adding an attribute provided in the package. 'cellWidth'. Refer the below code.
<carousel [cellsToShow]=5 [cellWidth]=250 [arrows]=false>
<div> Your content </div>
</carousel>
Since the attribute supports property binding we can try giving width of cells according to the screen size from typeScript file. I've not tried with that but the above code worked for me for laptop screen.
I want to bind the height of one angular component to the height of a div. I am trying to use template reference to fetch the height.
Is it possible to do so using this method in a clean way? I want to do it something like this in snippet below.
<div [style.height.px]="section1.offsetHeight"></div>
<app-custom-tag #section1>
</app-custom-tag>
I want the height of <div> to be equal to height of <app-custom-tag>
I can't use css column layout for this as these two elements are not positioned together.
I think there are a few extra things you'll have to do.
When you reference a component inside the view, you'll get the class instance. With that in mind, you can inject the ElementRef so you can get information about the native element.
Consider this example:
foo.component.ts
#Component({
selector: 'foo',
template: `foo`,
styles: [`:host { color: red; display: block; height: 300px; } `]
})
export class FooComp {
get offsetHeight () {
return this.el.nativeElement.offsetHeight;
}
constructor (private el: ElementRef) { }
}
app.component.ts
#Component({
selector: 'my-app',
template: `
<foo #f></foo>
{{ f.offsetHeight }}
<br>
<div style="border: 1px solid black" [style.height.px]="f.offsetHeight"></div>
<!-- <div style="border: 1px solid black" [ngStyle]="{ height: f.offsetHeight + 'px' }"></div> -->
<br>
<input #i id="demo" type="text">
{{ i.id }}
`,
})
export class AppComponent { }
When you reference a DOM element in the view, you'll get that DOM element.
ng-run demo.
I use this to create card game. Now pictures are loaded directly after the rendering of the card component with background-image. Therefore sometimes there are friezes. I want all the pictures to be loaded before showing the main screen using a preloader. Tell me please how to do this. Thank you.
import React from 'react';
import '../styles/Card.css';
const Card = (props) => {
const cardClick = () => {
if(props.status === 'unselected') {
props.onCardClick(props.cardIndex);
}
};
return (
<div className={`card card-${props.cardName} card-${props.status}`} onClick={cardClick}>
<div className="card-inner">
<div className="card-face card-front"></div>
<div className="card-face card-back"></div>
</div>
</div>
);
}
export default Card;
/*Set background to cards*/
.card-0C .card-front {
background: url('../images/cards/0C.png');
background-size: cover;
}
.card-0D .card-front {
background: url('../images/cards/0D.png');
background-size: cover;
}
.card-0H .card-front {
background: url('../images/cards/0H.png');
background-size: cover;
}
.card-0S .card-front {
background: url('../images/cards/0S.png');
background-size: cover;
}
.card-2C .card-front {
background: url('../images/cards/2C.png');
background-size: cover;
}
.card-2D .card-front {
background: url('../images/cards/2D.png');
background-size: cover;
}
Well there are a few ways. I'm gonna try and do my best to explain what you can do.
Use html preload attribute. reference here
The preload value of the link element's rel attribute allows you to
write declarative fetch requests in your HTML head, specifying
resources that your pages will need very soon after loading, which you
therefore want to start preloading early in the lifecycle of a page
load, before the browser's main rendering machinery kicks in. This
ensures that they are made available earlier and are less likely to
block the page's first render, leading to performance improvements.
This article provides a basic guide to how preload works.
<link rel="preload" href="style.css" as="style">
<img rel="preload" src="image.png" as="image" />
NOTE: you would have to ditch the background css usage.
Use actual styled html for the cards.
This is more complex way of doing what you want. Dropping the images and using straight up html styled with css. This is perfectly doable and adds the bonus of complex animations to the cards elements if you ever do so desire.
Use SVGs
This one is very similar to the HTML option because you would have to use an svg-loader to make it go straight into your html.
Declare all your images in a hidden div making sure that the browser has your images loaded always. reference here
This one is a bit meh but does the job nonetheless.
It consists of having a hidden div like so:
div#preload { display: none; }
Then your app would load images
// assuming you have the proper loaders configured
const cardOne = require("path/to/card1/img");
const cardTwo = require("path/to/card2/img");
...
render() {
return (
<div id="preload">
<img src={cardOne} />
<img src={cardTwo} />
{/* etc... */}
</div>
);
}
This div would always be rendered ensuring the browser loaded the images on first contact and your app would have the images cached and you could use a background solution like shown in the link:
#element_01 {
background: url(path/image_01.png) no-repeat;
display: none;
}
#element_02 {
background: url(path/image_02.png) no-repeat;
display: none;
}
#element_03 {
background: url(path/image_03.png) no-repeat;
display: none;
}
Problem: I want a single component (spacer) that will have width 100% and a height that can be input wherever it appears in the HTML (home.html in this test):
number 1
<spacer height="'200px'"></spacer>
no more
The spacer.html:
<div class="container-fluid spaceContainer" [ngStyle]="{'height': 'height'}">
spacer is here <<<--- this text is just for testing
</div>
The scss:
.spaceContainer {
width: 100%;
border: 1px solid red;
display: flex;
flex-direction: row;
}
Spacer.ts:
import {Component, Input, OnInit} from '#angular/core';
#Component({
selector: 'spacer',
templateUrl: './spacer.component.html',
styleUrls: ['./spacer.component.scss']
})
export class SpacerComponent implements OnInit {
#Input() height: string;
constructor() {
}
ngOnInit() {
console.log('height is '+ this.height);
}
}
When it runs, the console.log gives: height is '200px'
but the height of the red-bordered box is just enough to hold the 'spacer is here' text.
I struggle understanding binding a bit so I've tried:
<spacer height="200px"></spacer>
Console: height is 200px, which I thought would work but no change. Not understanding attr, I tried variants of attr.height.
This has to be easy and may help clear up my misunderstanding of how binding works.
Thanks in advance,
Yogi
Your mistake is located at this line:
[ngStyle]="{'height': 'height'}"
^^^^^^^^^^
it should be just height
You're binding height to string 'height' but you should bind it to height property of your component something like:
[ngStyle]="{'height': height}">?
or
[style.height]="height"
I'm trying to change a div background image on hover, I want to do this with JaveScript so that it works cross browser without any issues. The current code I have is:
<div class="staff" style="background-image: url(/wp-content/uploads/2013/08/IMG_1828- 300x237.png);" onmouseover="this.style.background=url(wp-content/uploads/2013/08/IMG_1836-v2-300x237.png);" onmouseout="this.style.background=url(wp-content/uploads/2013/08/IMG_1828-300x237.png);">
</div>
CSS:
.staff{
width: 300px;
height: 237px;
}
Can anybody see what is causing the problem?
<style>
.staff{
width: 300px;
height: 237px;
background-image: url(/wp-content/uploads/2013/08/IMG_1828- 300x237.png);
}
.staff:hover {
background-image: url(wp-content/uploads/2013/08/IMG_1836-v2-300x237.png);
}
</style>
<div class="staff"></div>
You can use simple css too.. and it will work on all browsers
.staff { background: url("url/img.png")}
.staff:hover { background: url("url/hoverimg.png")}
<div class="staff"></div>
Better use CSS than inline CSS and javascript to achieve the effect.
If you still want to do it inline, here is a example.
jsfiddle
onmouseover="javascript: this.style.backgroundImage = 'url(\'image_url\')'";
you can use css like this:
.staff{
width: 300px;
height: 237px;
background-image: url("/wp-content/uploads/2013/08/IMG_1828- 300x237.png");
}
.staff:hover{
background-image: url("wp-content/uploads/2013/08/IMG_1836-v2-300x237.png");
}
or javascript like:
onmouseover="javascript: this.style.backgroundImage = 'url(\'image_url\')'";
WORKING DEMO
CHANGE I MADE
onmouseover="this.style.background='url()';"
You have to enclose the url in single qoutes...
I would also suggest you use CSS rather than JS to do this. But since you asked how to do it in JS, this is your answer
Most browser should support :hover in css, so there is no need to use JavaScript for this (relevant fiddle here):
.staff{
width: 300px;
height: 237px;
background-image: url("/wp-content/uploads/2013/08/IMG_1828- 300x237.png");
}
.staff:hover{
background-image: url("wp-content/uploads/2013/08/IMG_1836-v2-300x237.png");
}
If you really want to use JavaScript, than you have to wrap url(...) in quotes like so:
<div class="staff"
style="background-image: url(/wp-content/uploads/2013/08/IMG_1828- 300x237.png);"
onmouseover="this.style.background='url(wp-content/uploads/2013/08/IMG_1836-v2-300x237.png)';"
onmouseout="this.style.background='url(wp-content/uploads/2013/08/IMG_1828-300x237.png);'">
</div>
I think you can use this script :
$('.staff').mouseover(function() {
$(this).attr('style',"background:grey;");
})
$('.staff').mouseout(function() {
$(this).attr('style',"background:white;");
})
Change the color to the image path.
$(document).ready(function(){
var staff = $(".staff"); //Avoid repeated traverse
$("img").hover(function(){
staff.css("background",'url(' + $(this).attr('src') + ')');
//Assuming you want to set current image as background image
});
$( "img" ).mouseout(function(){
staff.css("background","none");
});
});
Okay this works for me so when you hover over an image the background of the set div is changed. So when ever you hover over an image .staff background is changed.
I believe that is what you want?