Angular 4 CSS DIV background-image binding doesn't work - css

template:
<div [style.background-image]="profileImage" ></div>
ts:
private profileImage: any;
private sanitizer:DomSanitizer
get photo from service:
this.profileImage = this.sanitizer.bypassSecurityTrustStyle("url("+ data.photo + ")");
The binding is not working. I checked Chrome Dev tools, photo is not downloaded. When refreshing the page, it is working fine, but it has to work when the value is set in service. Tried with ngStyle also, it is not working.
Plunkr link https://plnkr.co/edit/IhVGjiImyfk0F1u6cWtG?p=preview

I updated a bit your code in order to work:
#Component({
selector: 'my-app',
template: `
<div [style.background-image]="profileImage" style="width: 961px; height: 688px;"></div>
<h2> {{message}}</h2>
`,
})
export class App {
profileImage: string;
message: string;
constructor(private sanitizer: DomSanitizer) {
this.message = "Before async";
}
async ngOnInit() {
await delay(2000);
this.message = "Updating Photo";
const url = 'https://4.bp.blogspot.com/--RBVfn6FzOI/Tq5kOxFGKEI/AAAAAAAACnM/LaiZLD0sUKY/s1600/cats.jpg';
this.profileImage = this.sanitizer.bypassSecurityTrustStyle(`url(${url})`);
}
}
Changes
1st: Change:
constructor(sanitizer: DomSanitizer)
into this:
constructor(private sanitizer: DomSanitizer)
Thus having the sanitizer as a member of the class in order to be accessible in ngOnInit().
2nd: Set the dimension of the <div>. This will not adjust automatically to your background image size. So I set width and height. Other solutions exist, like using the aspect ratio of the image, or keeping an invisible <img>. These and more are described in this answer.
3nd: Set the image HTTP scheme from http to https because you are receiving a warning in Plunker which serves content over https.
Updated Plunk

Related

Prevent Angular 15 iframe update browser history

I have an Angular 15 app with an iframe where I render html content from file.
Since this content may be changed by user I update src value. This affects browser history stack.
I was googling and found here Angular 7 iframe history back button trouble how to solve the issue. There is only one problem. My src variable is base64 content.
This is what I was using before and it renders fine but affects location stack:
.html
<div class="form-data">
<iframe width="100%" height="100%" [src]="layoutPath"></iframe>
</div>
.ts
private dbLayout: string;
layoutPath: SafeHtml;
ngOnInit() {
this.myService.getLayoutFromApi$().subscribe(result => this.dbLayout = result);
}
userChangeSomeContentOfHtml(someUserContent: string) {
const base64Layout = Base64.encode(dbLayout+ someUserContent);
this.layoutPath = this.sanitizer.bypassSecurityTrustResourceUrl("data:text/html;base64," + base64Layout);
}
}
According to solution from above link I updated my code to this:
.html
<div class="form-data">
<iframe #iframe width="100%" height="100%"></iframe>
</div>
.ts
private dbLayout: string;
ngOnInit() {
this.myService.getLayoutFromApi$().subscribe(result => this.dbLayout = result);
}
userChangeSomeContentOfHtml(someUserContent: string) {
const base64Layout = Base64.encode(dbLayout+ someUserContent);
const layouthPath = this.sanitizer.bypassSecurityTrustResourceUrl("data:text/html;base64," + base64Layout);
this.iframe.nativeElement.contentWindow.location.replace(layoutPath);
}
}
Unfortunately variable layoutPath is base64 and location.replace leads me to nowhere.
How can I solve this location stack bypass with a base64 content?

Tailwind + Nuxt 3 SSR dynamic class to child component not working

I'm facing an extrange behavior trying to implement dynamic class by props on child element when using Nuxt 3 SSR + Tailwind.
My parent component includes a child component
<section-latest-news :count="12" :columns="4" />
My child component tries to render columns based on columns property
<template>
<p class="text-xl text-center uppercase font-semibold border-b-2 mb-4 pb-1 tracking-widest">Últimas noticias {{gridCols}}</p>
<div :class="`grid gap-5 md:grid-cols-${columns}`" >
<div v-for="post in posts" :key="post.id" class="md:mb-0">
<post-card-image :post="post" />
</div>
</div>
</template>
<script setup>
import camelcaseKeys from 'camelcase-keys'
const props = defineProps({
excludeSlug: {
type: String,
required: false
},
count: {
type: Number,
required: false,
default: 6
},
columns: {
type: Number,
required: false,
default: 3
}
})
const runtimeConfig = useRuntimeConfig()
const route = useRoute()
const { data: posts } = await useFetch(`/public/latest`, {
params: {
count: props.count,
exclude_slug: props.excludeSlug
},
key: route.fullPath,
baseURL: runtimeConfig.public.apiBase,
transform: (response) => {
return camelcaseKeys(response, {deep: true})
}
})
</script>
For some reason, despite I correctly see the class md:grid-cols-3 in dev tools elements inspector, the class is not applied.
Please note that if I manually set the class without using backticks, the class works as expected, so it's not about CSS layout.
I'm guessing that is something related to SSR and lifecycle, but not sure how to fix it.
Actually, you cannot use dynamic classes with Tailwind: https://tailwindcss.com/docs/content-configuration#dynamic-class-names
Nothing related to Nuxt, interpolating a utility class is just not feasible since all the classes need to be known ahead of time (during the build): getting written in their full name in the code.
Here is how you can still achieve a similar result, but with more work of course.

How to dynamically change styleUrls or style in Angular?

I want to allow users to customize colors and some styles in Angular application. For that I want to make something like this
Structure:
component-one
  folder-with-css-files
    style-for-component-1-for-client1.css
    style-for-component-1-for-client2.css
    style-for-component-1-for-client3.css
    style-for-component-1-for-client4.css
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.style-for-component-1-for-client{clientId}.css'],
})
export class AppComponent implements OnInit {
clientId: string;
ngOnInit(): void {
// pseudocode
clientId = service.fetchClientId() // for example
}
}
How I can achieve that? I want to have some css files for every component and depend on user id I want to assign them to styleUrls. Someone can tell me how to do it?
You can use scss and wrap every stylesheet in a different class then based on the user’s selection change the class of your body.
Something like:
DarkMode.scss
.darkMode{
your first css here…
}
LightMode.scss
.lightMode{
your second css here…
}
index.html:
<body class="lightMode"></body>
Doing the above will by default apply the lightMode styling and if you remove the classes of your body in any of your components and replace it with darkMode then the darkMode styling will apply.
Adding/Removing class to/from body:
constructor(private renderer: Renderer2) {}
addClass(){
this.renderer.addClass(document.body, 'className');
}
removeClass(){
this.renderer.removeClass(document.body, 'className');
}
Adding/Removing the class does not have to be only in the index.html file, all you need to do is have a tag with a certain class that wraps around your whole code. For example in one of your components:
component.html:
<div [class]="className">
the rest of your html here...
</div>
component.scss:
.greenDefault{
green default css here...
}
.redDefault{
red default css here...
}
.greyDefault{
grey default css here...
}
component.ts
className: string;
changeStyle(class: string){
this.className = class;
}

Cant overwrite the custom stylesheet

I am trying to overwrite the CSS of react range slider.It uses the custom style sheet of which i need to add in the head section.My project is built on next.js
<link rel="stylesheet" href="https://unpkg.com/react-rangeslider/umd/rangeslider.min.css" />
Otherwise, the slider doesn't show anything if i don't add the link in head even though I installed the library. It's not even overwriting the CSS. I want to change the background color.This is my code:
import React, { Component } from 'react'
import 'react-rangeslider/lib/index.css';
import './slider.css';
import Slider from 'react-rangeslider'
class Horizontal extends Component {
constructor (props, context) {
super(props, context)
this.state = {
value: 850
}
}
handleChangeStart = () => {
console.log('Change event started')
};
handleChange = value => {
this.setState({
value: value
})
};
handleChangeComplete = () => {
console.log('Change event completed')
};
render () {
const { value } = this.state
return (
<div>
<div className='slider' style={{ marginTop:'165px',marginLeft:'319px',width:'700px',backgroundColor:'EF5350'}} >
<div style={{ textAlign:'center',color:'gray',fontSize:'35px',marginBottom:'82px'}}>
<p> What is the size of your property?</p>
</div>
<Slider
min={850}
max={5000}
value={value}
onChangeStart={this.handleChangeStart}
onChange={this.handleChange}
onChangeComplete={this.handleChangeComplete}
/>
<div className='value'>{value}</div>
</div>
</div>
)
}
}
export default Horizontal
I tried to change the background color in slider.css.
.rangeslider-horizontal .rangeslider__fill {
background-color: red;
}
The library needs to be installed first:
npm install react-rangeslider --save
It doesn't work as the slider stylesheet overwrite yours. Include the style like
// To include the default styles
import 'react-rangeslider/lib/index.css'
// import your css
import './style.css';
Demo
always make your own CSS stylesheet file the last file to import after any other CSS stylesheet files to make overwrite you need
otherwise, you can always use the console in the browser to auto-detect any error by pressing F12 in the browser then go to the tab called (console)
I think you can style element you want to live in the console to know the detail of how to nesting element
you also can open the CSS file in the editor and press Ctrl+F then find the line of code you want to style then copy its property and value to your own CSS file and then you can edit it so easy

Angular form validation and bootstrap styles

I'm quite new with Angular and i'm trying to create a registration form using Angular and Bootstrap 4.
The result i'd like is to use the styles of Bootstrap with the validation of Angular.
More precisely, when validating the form, Angular applies styles (ng-valid, ng-invalid, etc.) in two different places: the input element and the form element.
Two questions:
1) As Bootstrap uses 'has-danger' and 'has-success' instead of 'ng-[in]valid', is it possible to configure angular to use these styles instead of the default one. Currently, i'm considering extending bootstrap by adding the angular styles (with #extend has-danger/success)
2) Angular applies the style to the input and form elements whereas bootstrap expects it on the form-group element. Is it possible to have angular put the style there instead of the input element (or both?)
I'm using reactive forms and i'd like to avoid things like (not tested):
<form>
<div class="form-group" [class.has-error]="!fg.get('username').valid" [class.has-success]="fg.get('username').valid">
<label>Username</label>
<input formControlName="username" type="text"/>
</div>
</form>
Is there a simple way (not too verbose) of achieving this?
If you're using SASS you can do the following with out needing to rewrite all the css.
.ng-touched.ng-invalid {
#extend .is-invalid;
}
Note: you'll need to be importing bootstrap as part of your SASS build instead of reference it directly.
If you're not using SASS it's pretty to install see here
Angular CLI SASS options
Another option is this directive:
import {Directive, HostBinding, Self} from '#angular/core';
import {NgControl} from '#angular/forms';
#Directive({
selector: '[formControlName],[ngModel],[formControl]',
})
export class BootstrapValidationCssDirective {
constructor(#Self() private cd: NgControl) {}
#HostBinding('class.is-invalid')
get isInvalid(): boolean {
const control = this.cd.control;
return control ? control.invalid && control.touched : false;
}
}
It simply adds the is-invalid class to each field, if the field is touched or invalid. It basically behaves the same as Oliver's SASS-solution, but get's along without SASS and might also have a smaller compiled output.
The best idea that came to me while looking at the angular docs is to use a directive.
My implementation works only with Reactive forms and if the element you want to apply the style contains the form control (which, if you use bootstrap is the case). Should be extended for compatibility with select and textarea.
import { Directive, ElementRef, Input, OnInit } from '#angular/core';
import { FormControl, FormGroup } from '#angular/forms'
#Directive({ selector: '[formValidationStyle]' })
export class FormValidationStyleDirective implements OnInit {
#Input('formValidationStyle') private formGroup: FormGroup;
private component: FormControl;
static VALID_STYLE: string = 'has-success';
static INVALID_STYLE: string = 'has-danger';
constructor(private el: ElementRef) { }
ngOnInit(): void {
let componentName: string;
let inputElement = this.el.nativeElement.querySelector('input');
if (inputElement) {
componentName = inputElement.getAttribute('formControlName');
}
if (!componentName) {
console.error('FormValidationStyleDirective: Unable to get the control name. Is the formControlName attribute set correctly?')
return;
}
let control = this.formGroup.get(componentName)
if (!(control instanceof FormControl)) {
console.error(`FormValidationStyleDirective: Unable to get the FormControl from the form and the control name: ${componentName}.`)
return;
}
this.component = control as FormControl;
this.component.statusChanges.subscribe((status) => {
this.onStatusChange(status);
});
this.onStatusChange(this.component.status);
}
onStatusChange(status: string): void {
let cl = this.el.nativeElement.classList;
if (status == 'VALID') {
cl.add(FormValidationStyleDirective.VALID_STYLE)
cl.remove(FormValidationStyleDirective.INVALID_STYLE)
} else if (status == 'INVALID') {
cl.add(FormValidationStyleDirective.INVALID_STYLE)
cl.remove(FormValidationStyleDirective.VALID_STYLE)
}
}
}
Example:
The component:
#Component({
selector: 'security-register',
templateUrl: './register.component.html'
})
export class RegisterComponent {
registerForm: FormGroup;
constructor(private http: Http, private fb: FormBuilder) {
this.registerForm = this.fb.group({
username: ['', Validators.required]
});
}
}
And its template:
<form [formGroup]="registerForm" novalidate>
<div class="form-group" [formValidationStyle]="registerForm">
<label class="form-control-label" for="dbz-register-username">Login</label>
<input formControlName="username" type="text" class="form-control" id="dbz-register-username" required>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Register</button>
</div>
</form>

Resources