How to set background image in angular 6? - html

Here i want to set placehoder image and for that i use commonurl path (this.commonUrlObj.commonUrl) instead of (http://localhost:3000) so how to set image in background-image using commonurl in angular 6?
category.component.html
<img [src]="url" style="height: 400px;width: 400px" [ngStyle]="{'background-image': getUrl()}">
category.component.ts
getUrl(){
return "url('this.commonUrlObj.commonUrl/placeholder.jpg')";
}
common-class.ts
export class CommonClass {
constructor(public commonUrl : string = 'http://localhost:3000'){};
}

getUrl(){
return "url('"+this.commonUrlObj.commonUrl+"'/placeholder.jpg')";
}

Maybe I didn't understand your problem but is this what you wanted to do ?
getUrl(){
return `url('${this.commonUrlObj.commonUrl}/placeholder.jpg')`;
}

You can't have an background image for an image. What you can do is wrap a div and give it an background:
getUrl(){
return "url('"+this.commonUrlObj.commonUrl+"'/placeholder.jpg')";
}
<div [ngStyle]="{'background-image': getUrl()}>
<img [src]="url" style="height: 400px;width: 400px">
</div>

As per docs in Angular.io you can give ngStyle an ObjExp. Like this.
TS
// Not in the question but don't use a constructor to define vars
private commonUrl: string = 'localhost:3000'; // Could have this as an env variable
getBackground() {
return {'background-image': `url(${this.commonUrl}/placeholder.png)`};
}
HTML
<div [ngStyle]="getBackground()"></div>

Related

How to use ngIf to choose diffrent selector in html in an angular app

I have a question about how to use ngIF in HTML code to choose different selector.
I show my code as follow:
in HTML Code:
<a class="style" (click)=clickFunction() (keyup.Enter)=ke()>
<div>
content
</div>
</a>
this is html is in a shared component,
I want to use this shared component into the other component with input parameter noClickAndKeyEnter=true |false
so in this case I should change html code as follow:
<a class="stype" (click)="noClickAndKeyEnter ? clickFunction(): ''" (keyup.Enter)="noClickAndKeyEnter ? ke() :''">
<div>
content
</div>
</a>
My question is, is there also the easy way to resolve my question, that I do not write all place with noClickAndKeyEnter ? :
any solutions?
There are multiple ways you can do this. The simplest could be:
clickFunction(){
if(this.noClickAndKeyEnter){
// execute code here
} else {
// just return or whatever you want here
}
}
You can use the callback pattern!
ts
conditionallyExecute(callback: Function, ...params) {
if(this.noClickAndKeyEnter) {
callback(params)
}
}
html
<a class="stype" (click)="conditionallyExecute(clickFunction, 1, 2)" (keyup.Enter)="conditionallyExecute(ke)">
<div>
content
</div>
</a>
Just a simple guard in your functions
clickFunction() {
if (!this.noClickAndKeyEnter) return;
...
}
ke() {
if (!this.noClickAndKeyEnter) return;
...
}
But by the name of noClickAndKeyEnter I think you might have the true / false values backwards.

Images not displaying when print using ngx-print library

As you can see , the images are shown correctly in the screen :
but when i try to print this container using ngx-print it's not displaying correctly :
Very important : I have no control over the images because they come from the back-end.
HTML :
<div class="hover-div">
<button mat-button class="title-div" printSectionId="card-container"
printTitle="professionalcard" [useExistingCss]="true" ngxPrint>
<div fxLayout="row">
<mat-icon class="preview-icon">print</mat-icon>
<div>print</div>
</div>
</button>
</div>
HTML of images :
<div class="simple-image" *ngIf="cardModel[r.content].value">
<img [src]="cardModel[r.content].value"
class="image-holder1">
</div>
Here is the result when i inspect the img in the page :
and this one , when i inspect the page viewer when printing :
i've noticed that in the last one , the link is not the right one , he is adding the directory of the page that i'm printing from , so how to fix this ?
According to this answer and this GitHub issue comment, you have to use absolute path for the image.
So, in your case, I think that something like this should work:
<img [src]="sanitizer.bypassSecurityTrustUrl('/' + cardModel[r.content].value)" />
import { DomSanitizer } from "#angular/platform-browser";
export class AppComponent {
constructor(private sanitizer: DomSanitizer) {}
}
you can add let window.location.origin to make it an absolute path , then you'll not have this problem

Is it possible to import typescript into html ans a color value or edit a color value from html in typescript

I have been working on this piece of code for like two days now. I am using Angular to create a web app, and I need some numbers to change color when they reach a certain value. (EXAMPLE: if num > 45 color = green else color = red) I would like to be able to pass the value of color between my typescript and HTML, but I'm having trouble with that. The color value passes to HTML just fine, but I can't put the color value into any type of style.
Here is my code. Thanks for the help!
Typescript:
colorOption=''
if(this.Classyaverage > 45){
console.log('red')
this.colorOption='#FF0000'
}
else{
console.log('green')
this.colorOption='#00FF00'
}
HTML:
<body>
<div class="pagecolor">
<div class="box">
<canvas class="offset"
id="lineChart"
width="240"
height="180"
>
</canvas>
//This is what I want...
<style>
h1{ color:{{colorOption}};}
</style>
<h1>
{{Classyaverage}}
</h1>
</div>
</div>
</body>
So is I can't import a Typescript like that, is it possible to export HTML or CSS into typescript?
Create a css class where you will apply the color:
.myColor {
color: var(--colorVariable);
}
Assign the value of the css variable from the typescript according to what you need in this way:
document.documentElement.style.setProperty( '--colorVariable', '#00FF00' );
You can modify it from any calculation or event of the application.
To achieve expected result, use ngStyle on h1 tag (https://angular.io/api/common/NgStyle)
<h1 [ngStyle]="{'color': colorOption}">
{{Classyaverage}}
</h1>
I think what you are looking for is the ngClass directive.
Here is the documentation from Angular. https://campuslabs.visualstudio.com/Student%20Assessment/_workitems/edit/59235
// .css
.red{
color: #f00;
}
.green: {
color: #0f0
}
-
// .html
<h1 [ngClass]="{'red': Classyaverage > 45, 'green': Classyaverage <= 45}"></h1>
This might be more than you need, but if you wanted to style multiple elements (such as all of a class or tag name) you could do the following.
HTML:
<h1 class="color-change">
{{Classyaverage}}
</h1>
<h2 class="color-change" *ngFor"let el of arr">
test
</h2>
TypeScript:
#ViewChildren(".color-change") private colorChange: QueryList<ElementRef>;
constructor(private renderer: Renderer2) { }
ngAfterViewInit(): void {
this.colorChange.subscribe(() =>
this.colorChange.forEach((element: ElementRef) => {
this.renderer.setStyle(
element.nativeElement,
'color',
this.colorOption
})
})
);
}
...
This would take care of multiple elements as well as asynchronous elements

Background images won't load dynamically

I'm trying to set the background image of a div dynamically using Angular 6...
But for some reason no matter what I do, It seems I can't make the image to render.
The images are being served from a local SimpleHTTPServer using python.
HTML:
<a *ngFor="let movie of movies">
<div [style.background-image]="movie.image">
{{movie.name}}
</div>
</a>
Component:
getMovies() : void {
this.movieService.getMovies().subscribe(movies => this.movies = movies.map(movie => {
movie.image = this.sanitizer.bypassSecurityTrustStyle(`url(${movie.image})`);
return movie;
}));
}
I've tried also using the sanitizer with no success... And i'm not getting any errors.
You can use like this:
<a *ngFor="let movie of movies">
<div [ngStyle]="{'background-image': 'url(' + movie.image + ')'}"> {{movie.name}}</div>
</a>
or
[style.backgroundImage]="'url('+ movie.image +')'"
Updated:
You should also mention height and width in div as mentioned by user184994 in comment section like this:
<div [ngStyle]="{backgroundImage: 'url(' + movie.image + ')', width: '200px', height: '150px'}"></div>
Make sure the url is URI Encoded.
In JS: encodeURI(url)

NgStyle with dynamic content proper syntax angular 4/2

I am using NgStyle to dynamically set the background image of a container in angular 4.
This site: Says the proper syntax is the following
[ngStyle]="{'background-image': venueobject.groupphoto[0]}">
or
[ngStyle]="{'background-image': 'venueobject.groupphoto[0]'}">
I also saw turning the whole thing into a string:
[ngStyle]="'background-image': 'url(' + 'venueobject.groupphoto[0]'+ ')'">
and
[ngStyle]="'background-image: url(' + venueobject.groupphoto[0] + ')'">
but I keep not getting it. The page is rendering so my html is not broken, but the image is not showing.
This is currently not yay and I am trying to make it yay.
Please help me make it yay
Hugs and kisses
You can try the following:
In your ts file:
import { DomSanitizer } from '#angular/platform-browser';
constructor(private sanitizer: DomSanitizer) { }
getBackgroundImg() {
// replace the path to your image here
const img = 'assets/img/wall.png';
const style = `background-image: url(${img})`;
// this is to bypass this warning 'WARNING: sanitizing unsafe style value background-image: url(assets/img/wall.png) (see http://g.co/ng/security#xss)'
return this.sanitizer.bypassSecurityTrustStyle(style);
}
In your html file:
<div [style]="getBackgroundImg()"></div>
You will also need to set the width and height of the div to see the image.