Angular 2 How to change component <body> background color for each component individually - css

I have component A and component B.
I want component A background color to be black.
I want component B background color to be yellow.
If I modify the bg color inside the main style.css then that color will be set globally in my app.
If I try to modify the bg color inside the component css file the body bg color will not be affected.
Is there a way to modify the bg color for each component individually when they load ?

#Component({... })
class MyComponent { constructor() {
this.bgColor = this.getRandomColor(); }
#HostBinding('style.background-color')
bgColor;
getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
}
Thanks for downvoting my answer because of the poor question title
Check instead other answers
- Style html,body from web component (Angular 2)
- Add class to body on Angular2
- Angular 2.x bind class on body tag
- ...

Related

Removing background image from label in tornadofx

I have two css classes on a tornadofx label bound to a SimpleBooleanProperty. One which has a background image and a blue border and one which has no background image and a yellow border.
Snippet from View containing label:
val switch: SimpleBooleanProperty = SimpleBooleanProperty(false)
label("my label"){
toggleClass(UIAppStyle.style1, switch.not())
toggleClass(UIAppStyle.style2, switch)
}
Snippet from UIAppStyle:
s(style1){
textFill = Color.YELLOW
maxWidth = infinity
maxHeight = infinity
alignment = Pos.CENTER
backgroundImage += this::class.java.classLoader.getResource("img.png")!!.toURI()
backgroundPosition += BackgroundPosition.CENTER
backgroundRepeat += Pair(BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT)
borderColor += box(Color.BLUE)
}
s(style2){
textFill = Color.YELLOW
maxWidth = infinity
maxHeight = infinity
alignment = Pos.CENTER
borderColor += box(Color.YELLOW)
}
When switch = false, there is a background image and a blue border. When switch = true, there is the same background image and a yellow border. I'm not finding out how to get the background image to remove. Interestingly enough, if I add a different background image to style2, it changes correctly.
Edit: To remove two toggleClasses and introduce new strange problem:
class MyView : View(){
...
init{
...
row{
repeat(myviewmodel.numSwitches){
val switch = myviewmodel.switches[it]
val notSwitch = switch.not()
label("my label"){
addClass(UIAppStyle.style2)
toggleClass(UIAppStyle.style1, notSwitch)
}
}
}
}
This code snippet does not work for me. However, if I add private var throwsArray = mutableListOf<ObservableValue<Boolean>>() as a field of MyView and add notSwitch to the array, then the same exact code works. It's almost as if notSwitch is going out of scope and becoming invalidated unless I add it to a local array in the class?
I don’t understand why you want to have two different toggleClass for the same control. As you pointed out, the problem in your case is that when the backgroundImage is set, you need to set a new one in order to change it. But in your case, you only have to add the style without backgroundImage first and them set toggleClass with the style with backgroundImage. Like this:
label("my label"){
addClass(UIAppStyle.style2)
toggleClass(UIAppStyle.style1, switch)
}
button {
action {
switch.value = !switch.value;
}
}
Edit: This ilustrate what I'm talking about in comments:
class Example : View("Example") {
override val root = vbox {
val switch = SimpleBooleanProperty(false)
val notSwitch = switch.not()
label("my label"){
addClass(UIAppStyle.style2)
toggleClass(UIAppStyle.style1, notSwitch)
}
button("One") {
action {
switch.value = !switch.value;
}
}
button("Two") {
action {
notSwitch.get()
}
}
}
}
You can put the notSwitch.get() in any action and without trigger that action it does the work. Check how I put it in the action of button Two, but without clicking that button even once, it works.
This is actually some kind of hack, in order to achieve what you want. But I don’t see the reason why my initial solution with true as default value for property shouldn’t work.
Edited to do inverse of status
Here is simple example of a working toggle class using your styling:
class TestView : View() {
override val root = vbox {
val status = SimpleBooleanProperty(false)
label("This is a label") {
addClass(UIAppStyle.base_cell)
val notStatus = SimpleBooleanProperty(!status.value)
status.onChange { notStatus.value = !it } // More consistent than a not() binding for some reason
toggleClass(UIAppStyle.smiling_cell, notStatus)
}
button("Toggle").action { status.value = !status.value }
}
init {
importStylesheet<UIAppStyle>()
}
}
As you can see, the base class is added as the default, while styling with the image is in the toggle class (no not() binding). Like mentioned in other comments, the toggleClass is picky, additive in nature, and quiet in failure so it can sometimes be confusing.
FYI I got to this only by going through your github code and I can say with confidence that the not() binding is what screwed you in regards to the toggleClass behaviour. Everything else causing an error is related to other problems with the code. Feel free to ask in the comments or post another question.

Change one color in all css style by javascript

I have a template with multiples class using one color, can I dynamically change that color to another using javascript?
When the page loads, locate all the div, span, p, h, with color #512a69 and change it to #ef7e8e.
Is it possible?
Thanks.
Here is a solution which I'll explain step-by-step.
First, call colorReplace("#512a69", "#ef7e8e");. The first value is the target color, and the second is the replacement color.
Inside it, $('*').map(function(i, el) { will select all tags in the DOM tree. For each element, its getComputedStyle(el) styles array is returned. You can customize the selector for faster processing (e.g. $('div').map(function(i, el)) {).
All style attributes containing "color" (e.g. background-color, -moz-outline-color, etc.), it will be checked if the color value is equal to your target color. If so, it will be replaced with the target color.
Colors are returned like rgba(0,0,0,0) or rgb(0,0,0), not like #FFFFFF, so a quick conversion is done from rgb to hex for the comparison. That uses the internal rgb2hex() function.
I hope this is what you are looking for.
function colorReplace(findHexColor, replaceWith) {
// Convert rgb color strings to hex
// REF: https://stackoverflow.com/a/3627747/1938889
function rgb2hex(rgb) {
if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb;
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
// Select and run a map function on every tag
$('*').map(function(i, el) {
// Get the computed styles of each tag
var styles = window.getComputedStyle(el);
// Go through each computed style and search for "color"
Object.keys(styles).reduce(function(acc, k) {
var name = styles[k];
var value = styles.getPropertyValue(name);
if (value !== null && name.indexOf("color") >= 0) {
// Convert the rgb color to hex and compare with the target color
if (value.indexOf("rgb(") >= 0 && rgb2hex(value) === findHexColor) {
// Replace the color on this found color attribute
$(el).css(name, replaceWith);
}
}
});
});
}
// Call like this for each color attribute you want to replace
colorReplace("#512a69", "#ef7e8e");
Source: https://stackoverflow.com/a/30724171/1136132

How can the background or the color in the navigation bar be changed?

Currently I couldn't find any method to change the color/background of the navigation bar in SwiftUI. Any tips?
In order to change color of navigation bar for all view controllers, you have to set it in AppDelegate.swift file
Add following code to didFinishLaunchingWithOptions function in AppDelegate.swift
var navigationBarAppearace = UINavigationBar.appearance()
navigationBarAppearace.tintColor = uicolorFromHex(0xffffff)
navigationBarAppearace.barTintColor = uicolorFromHex(0x034517)
In here tintColor attribute change the background color of the navigation bar.
barTintColor attribute affect to the color of the:
back indicator image
button titles
button images
Bonus:
Change color of navigation bar title:
// change navigation item title color
navigationBarAppearace.titleTextAttributes =[NSForegroundColorAttributeName:UIColor.whiteColor()]
titleTextAttributes affect to the title text
I hope it helps. :)
In SwiftUI, at this point we can not change it directly, but you can change navigationBar appearance like this,
struct YourView: View {
init() {
UINavigationBar.appearance().backgroundColor = .orange
//Use this if NavigationBarTitle is with Large Font
UINavigationBar.appearance().largeTitleTextAttributes = [.font : UIFont(name: "Georgia-Bold", size: 20)!]
//Use this if NavigationBarTitle is with displayMode = .inline
//UINavigationBar.appearance().titleTextAttributes = [.font : UIFont(name: "Georgia-Bold", size: 20)!]
}
var body: some View {
NavigationView {
Text("Hello World!")
.navigationBarTitle(Text("Dashboard").font(.subheadline), displayMode: .large)
//.navigationBarTitle (Text("Dashboard"), displayMode: .inline)
}
}
}
I hope this will help you. Thanks!!
Till now there is no definitive API in SwiftUI for this purpose. But you can use the appearance API. Here is a sample code.
import SwiftUI
struct ContentView : View {
init() {
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.red]
UINavigationBar.appearance().backgroundColor = .green
}
var body: some View {
NavigationView {
NavigationButton(destination: SecondPage(), label: {
Text("Click")
})
.navigationBarTitle(Text("Title"), displayMode: .inline)
}
}
}
Put a Rectangle behind your NavigationView inside a ZStack:
ZStack {
Rectangle().foregroundColor(.red)
NavigationView {
...
}
}
Please see this answer for a solution that does not use .appearance().
In short use UIViewControllerRepresentable
func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<NavigationConfigurator>) {
uiViewController.navigationController?.navigationBar...
}
With Introspect you could do it this way:
NavigationView {
Text("Item 2")
.introspectNavigationController { navigationController in
navigationController.navigationBar.backgroundColor = .red
}
}
One thing to note that I didn't at first understand: SwiftUI will change the appearance of things like NavigationBar based on whether you are in night mode.
If you want to default it to a different color scheme add
.colorScheme(.dark)
If you create a color scheme using the color set system as outlined in this post: https://www.freecodecamp.org/news/how-to-build-design-system-with-swiftui/ it would apply to the main elements like navigations and tab bars, and allow you to apply different schemes for night/day mode.
The NavigationView is managing full screens of content. Each of those screens has its own background color. Therefore you can use the following approach to apply your Background color onto the screens:
let backgroundColor = Color(red: 0.8, green: 0.9, blue: 0.9)
extension View {
func applyBackground() -> some View {
ZStack{
backgroundColor
.edgesIgnoringSafeArea(.all)
self
}
}
}
Then you apply it to all your screens:
NavigationView {
PrimaryView()
.applyBackground()
DetailView(title: selectedString)
.applyBackground()
}
Be aware: some SwiftUI views have their own background color which is overriding yours (e.g. Form and List depending on context)
iOS 16
You can set any color to the background color of any toolbar background color (including the navigation bar) for the inline state with a simple native modifier:
Xcode 14 beta 5 (Not working 🤦🏻‍♂️, waiting for beta 6...)
.toolbarBackground(.yellow, for: .navigationBar)
Xcode 14 beta 1,2,3,4
.toolbarBackground(.yellow, in: .navigationBar)
Note that the color will set on the entire bar (up to the top edge of the screen).
Also, the color will be animated during the transition between Large and Inline modes of the bar.

how to change color of the text based on background color on run time css

I have
<span [ngStyle]="{'background-color': dynamicColor}">ABC</span>
I want to set the font color of text based on the background color that is inverted color of background-color so that is easily readable. Like if background-color is white then text color should be black. And if background-color is black then text color is white.
In sass, I could do this easily using the following function
// function to return the text-color based on the passed background color
#function text-color($color) {
#if (lightness($color) > 50) {
#return #000000; // Lighter backgorund, return dark color
}
#else {
#return #ffffff; // Darker background, return light color
}
}
but the background-color is getting changed run time based on the dynamic content using AJAX.
Update
Added more detail to clear the question.
When ngStyle change, color while change!
element:
<span ngStyle="{\"backgroundColor\":\"#000\"}">ABC</span>
js:
setTimeout(function() {
var dom = document.querySelector("[ngStyle]");
var temp = JSON.parse(dom.getAttribute("ngStyle"));
dom.style.color = (temp.backgroundColor === "#000" ? "#fff" : "#000")
}, 16)

Change JavaFX MenuButton Icon

Is there a simple way to change a JavaFX MenuButton arrow to a character or hide it completely?
MenuButton hamburgerMenu = new MenuButton("\u2630");
hamburgerMenu.getItems().addAll(new MenuItem("Ham"), new MenuItem("Buger"));
Add the following style to hide the arrow
.menu-button > .arrow-button > .arrow {
-fx-background-color: transparent;
}
Result
You can also define a different SHAPE using -fx-shape followed by a SVG path.
.menu-button > .arrow-button > .arrow {
-fx-shape: "M 0 -3.5 v 7 l 4 -3.5 z";
}
The output is
There are several ways to do this, here are four. The code is Jython with JavaFX. You can edit this code to meet your needs.
First, the enum, for context.
public enum URLBarArrowConstants {
//URLBarArrow Constants
BYCSS_AND_SHAPE,
BYCSS_AND_NO_SHAPE,
NOCSS_AND_SHAPE,
NOCSS_AND_NO_SHAPE;
}
Second, the css files, for context.
EG #1
/*ComboBox's Arrow is a Region.*/
.menu-button .arrow-button .arrow {
-fx-shape: "...";
-fx-scale-shape: true;
-fx-position-shape: true;
}
EG#2
/*ComboBox's Arrow is a Region.*/
.menu-button .arrow-button .arrow {
/*Setting either of these two will do.*/
-fx-background-color: transparent;
-fx-opacity: 0.0;
}
/*ComboBox's Arrow Button is a Stack Pane.*/
.menu-button .arrow-button{
-fx-background-position: center;
-fx-background-repeat: no-repeat;
-fx-background-image: url("..<file>.png");
}
The method, in my main file.
def setCustomURLBarArrow(self, url_bar, scene, URLBarArrowConstant):
from javafx.scene.paint import Paint
from javafx.scene.shape import Shape, SVGPath, FillRule
Don't configure the ComboBox Arrow by CSS, instead, do it programmatically and change the Regions SVG Shape
if URLBarArrowConstant == URLBarArrowConstants.NOCSS_AND_SHAPE:
#SVG Object
previous_url_bar = SVGPath()
#SVG Path
previous_url_bar.setContent("...") # edit this
#SVG Fill Rule
previous_url_bar.setFillRule(FillRule.NON_ZERO)
#Set Fill --
previous_url_bar.setFill(Paint.valueOf(Color.web("...").toString())) //edit here
#Apply CSS Sheet
url_bar.applyCss()
#Set Region's Shape
arrow_region = url_bar.lookup(".arrow").setShape(previous_url_bar)
Configure the ComboBox Arrow by CSS and change the Regions SVG Shape
elif URLBarArrowConstant == URLBarArrowConstants.BYCSS_AND_SHAPE:
#Apply Stylesheet for URL Bar
scene.getStylesheets().add(File("..<file>.css").toURI().toString()) //edit here
Configure the ComboBox Arrow by CSS but instead, merely hide the arrow by setting the transparency/opacity values and set a background.
elif URLBarArrowConstant == URLBarArrowConstants.BYCSS_AND_NO_SHAPE:
#Apply Stylesheet for URL Bar
scene.getStylesheets().add(File("..<file>.css").toURI().toString()) //edit here
Don't configure the ComboBox Arrow by CSS, instead, do it programmatically and merely hide the arrow by setting the transparency/opacity values and set a background.
elif URLBarArrowConstant == URLBarArrowConstants.NOCSS_AND_NO_SHAPE:
from javafx.scene.paint import Paint
from javafx.scene.layout import CornerRadii
from javafx.scene.layout import Background, BackgroundSize, BackgroundImage, BackgroundPosition, BackgroundRepeat, BackgroundFill
#Apply CSS Sheet
url_bar.applyCss()
#Grab Arrow(Region), ArrowButton(StackPane) ComboBox properties
arrow_region = url_bar.lookup(".arrow")
arrow_button = url_bar.lookup(".arrow-button")
#Either Set Opacity to 0 or set background color to transparent.
arrow_region.setOpacity(0.0)
arrow_region.setBackground( Background( array(BackgroundFill, [BackgroundFill( Paint.valueOf(Color.TRANSPARENT.toString()), CornerRadii.EMPTY, Insets.EMPTY)]) ) )
#Set a Background Image for the .arrow-button StackPane.
arrow_button.setBackground(Background( array(BackgroundImage, [BackgroundImage( Image( String(File('..<file>.png').toURI().toString()), True) , BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, BackgroundSize.DEFAULT)] ) ) ) //if you want, edit this

Resources