How to Change <Body> Tag Style from Child Component

How to change body tag style from child component?

Use ::ng-deep, like so:

CSS

::ng-deep .light-gray{
background-color: red;
}

DEMO


Use ViewEncapsutation.None:

CSS

.light-gray{
background-color:red
}

Class:

import { ViewEncapsulation } from '@angular/core';
...
@Component({
...
encapsulation: ViewEncapsulation.None

DEMO

Style html,body from web component (Angular 2)

You could try

body {
/* body styles here */
}

but styles in components are not supposed to be applied to elements outside themselves.

Another way is to use body as selector in your main component and use host-binding to set/remove a CSS class on body to make CSS you added to your index.html match.

@Component({
selector: "body",
host: {
"[class.some-class]":"someClass"
},
})
export class AppComponent {
constructor(private loginService: LoginService) {
loginService.isLoggedInChanged.subscribe((value) => {
this.someClass = value;
});
}
someClass: bool = false;
}

when you set someclass to true (usind some binding to a service, the class gets added to the body.

If you don't want to add CSS globally you can also bind to a style attribute directly

@Component({
selector: "body",
host: {
"[style.background-image]":"bodyBackgroundImage()"
},
})
export class AppComponent {
bool isLoggedIn = false;
constructor(private loginService: LoginService) {
loginService.isLoggedInChanged.subscribe((value) => {
this.isLoggedIn = value;
});
}
function bodyBackgroundImage() {
return this.isLoggedIn ? 'url("gradient_bg.png")': 'none';
}
}

update

DomAdapter is gone. Renderer2 should provide similar functionality.

A way to style <body> directly from the login component is to use the DomAdapter (see also https://github.com/angular/angular/issues/4942)

System.import('angular2/src/platform/browser/browser_adapter').then(function(browser_adapter) {
browser_adapter.BrowserDomAdapter.makeCurrent();
})
...
_dom: DomAdapter = new BrowserDomAdapter();
_dom.setStyle(_dom.query('body'), 'padding', '50px');

How to style body tag with CSS-in-JS approach?

With Emotion you can set something up, like the following create-react-app example, to inject global styles:

import React from 'react';
import ReactDOM from 'react-dom';
import { Global, css } from '@emotion/core'

const bodyFillColor = `rgb(218,236,236)`;

class App extends React.Component {
render() {
return(
<div>
<Global
styles={css`
body {
background: ${bodyFillColor};
margin: 0;
padding: 0;
min-height: '100vh';
max-width: '100vw';
}
`}
/>
<Global
styles={{
'body.noScroll': {
// Prevent scrolling; conditionally activate this
// in subcomponents when necessary ...
overflow: 'hidden',
},
}}
/>
</div>
);
}
}

ReactDOM.render(
<App />,
document.getElementById('root')
);

This shows an example of injecting a style on the body and also assigning a class to the body that can conditionally be activated later on.

eg.

{this.state.activate && <Global styles={{`stylesetc`}}/>}

https://emotion.sh/docs/globals

Alternative

StyledComponents uses a CSS-in-JS approach and works great with React applications. This is a technique I've used in the past straight from the documentation:

import { createGlobalStyle } from 'styled-components'

const GlobalStyle = createGlobalStyle`
body {
color: ${props => (props.whiteColor ? 'white' : 'black')};
}
`

// later in your app

<React.Fragment>
<Navigation /> {/* example of other top-level stuff */}
<GlobalStyle whiteColor />
</React.Fragment>

How to style child components from parent component's CSS file?

Update - Newest Way

Don't do it, if you can avoid it. As Devon Sans points out in the comments: This feature will most likely be deprecated.

Last Update

From Angular 4.3.0 till even now (Angular 12.x), all piercing css combinators were deprecated. Angular team introduced a new combinator ::ng-deep as shown below,

DEMO : https://plnkr.co/edit/RBJIszu14o4svHLQt563?p=preview

styles: [
`
:host { color: red; }

:host ::ng-deep parent {
color:blue;
}
:host ::ng-deep child{
color:orange;
}
:host ::ng-deep child.class1 {
color:yellow;
}
:host ::ng-deep child.class2{
color:pink;
}
`
],

template: `
Angular2 //red
<parent> //blue
<child></child> //orange
<child class="class1"></child> //yellow
<child class="class2"></child> //pink
</parent>
`

Old way

You can use encapsulation mode and/or piercing CSS combinators >>>, /deep/ and ::shadow

working example : http://plnkr.co/edit/1RBDGQ?p=preview

styles: [
`
:host { color: red; }
:host >>> parent {
color:blue;
}
:host >>> child{
color:orange;
}
:host >>> child.class1 {
color:yellow;
}
:host >>> child.class2{
color:pink;
}
`
],

template: `
Angular2 //red
<parent> //blue
<child></child> //orange
<child class="class1"></child> //yellow
<child class="class2"></child> //pink
</parent>
`

How to inherit css styles in child component from parent in Angular 5

Why make things complex?

Ideal way to do would be to add refrence of parent css file in child component as well.

 @Component({
selector: 'child-app',
templateUrl: `./child.component.html`,
styleUrls:['./parent/parent.component.css', './child.component.css']
})
export class ChildComponent { }

How do I change the HTML/CSS of a child component from parent in Angular 2+?

You can come up with solution via the @Input() decorator of angular combined with dynamic scss/css class assigning in angular. In your child component you can assign dynamic css via like this

`[ngClass]="{'CSS-CLASS': CONDITION-HERE,'CSS-CLASS':CONDITION-HERE}"`

In your specific case child component.html:

<div *ngfor = "let record in records">
<table>
<tr>
<td> [ngClass]="{'foo': record==record.name=='foo'}" {{ alias }} </td>
</tr>
</table>
</div>

PS:- You can edit the condition for class 'foo' according to your needs.

In your child component.ts:

   export class ChildComponent implements OnChanges {

@Input() public rercord: any[];

constructor() {
}
}

Whenever you want use child component in the parent component just use the following:

<body>
<child-component [records]="fetchedRecords"></child-component>
</body>

Inside parent component.ts:

export class ParentComponent {

public fetchedRecords: any;

constructor(public myService:MyService) {
this.myService.getValues().subscribe((rowData)=>{
this.fetchedRecords = rowData;
});
}
}

How to style body element in MUI

Material-UI v5

You can change the body styles by overriding MuiCssBaseline styles in createTheme():

import CssBaseline from "@mui/material/CssBaseline";
import darkScrollbar from "@mui/material/darkScrollbar";
import { createTheme, ThemeProvider } from "@mui/material/styles";

const theme = createTheme({
components: {
MuiCssBaseline: {
styleOverrides: {
body: {
...darkScrollbar(),
color: "darkred",
backgroundColor: "grey",
"& h1": {
color: "black"
}
}
}
}
}
});

export default function GlobalCssOverride() {
return (
<ThemeProvider theme={theme}>
<CssBaseline />
<Content />
</ThemeProvider>
);
}

Edit GlobalCssOverride Material Demo (forked)

Material-UI v4

You can apply the styles to the body using @global class like this:

const useGlobalStyles = makeStyles({
"@global": {
body: {
backgroundColor: "tomato"
}
}
});
const theme = createMuiTheme({});

function MyThemeProvider({ children }) {
useGlobalStyles();
return <ThemeProvider theme={theme}>{children}</ThemeProvider>;
}

function App() {
return (
<MyThemeProvider>
<Button variant="contained" color="primary">
Button
</Button>
</MyThemeProvider>
);
}

If you create the project by create-react-app, you can also use css/scss module to style any element globally:

/* styles.css */
body {
color: white;
font-size: 15px;
}
import React from "react";
import Button from "@material-ui/core/Button";
import "./styles.css";

function App() {
return (
<Button variant="contained" color="primary">
Hello World
</Button>
);
}

Live Demo

Edit 64705335/how-to-style-body-element-in-materialui



Related Topics



Leave a reply



Submit