Styling child components template from parent component css angular - css

How to force CSS of child component from parent using ::ng-deep or something?
I have parent component where I put child component:
....parent.component...
<app-likes></app-likes>
.....parent.component......
Not inside that likes component there is he following HTML:
<div class="mainDiv">
<div class="secondDiv"><i class="far fa-heart fa-3x"></i></div></div>
Now I want to set color of fa-heart class to white from parent parent.component.css.
How can I do that?

You can do this way, in the css of the parent component:
parent.component.css:
:host ::ng-deep .fa-heart {
color: red;
}
or
:host ::ng-deep app-likes .fa-heart {
color: red;
}

Well I will go against the folks above and suggest that you don't do this.
If you consider the component an isolated building block in your app, you would consider it an advantage, that it looks the same in every place you use it. Using ::ng-deep to override this behaviour will cause you trouble in larger apps.
Angular promotes using #Inputs as the interface of passing data into the component. My suggestion is to use #Input to modify the view. Or, if in larger contexts you can use Dependency Injection to provide a token that specifies a theme for all children of a component.
<app-likes theme="white"></app-likes>
#Component({selector: 'app-likes'})
class AppLikesComponent {
#Input() theme: string;
#HostBinging("class") get themeBinding() {
return 'theme--' + this.theme;
}
}

You could set the ViewEncapsulation option in the parent component to remove the shadow DOM. This essentially allows the child component to use the selector definitions from the parent component.
Try the following
Parent component
import { Component, ViewEncapsulation } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ],
encapsulation: ViewEncapsulation.None // <-- no shadow DOM
})
export class AppComponent {
}
Parent CSS
.fa-heart {
color: white;
}
Working example: Stackblitz

Related

Is there some way with which i can apply css dynamically to my child component?

I have a component which is reusable. This component is called from parent component multiply times and sometimes the background page of the parent component is white and sometimes is black.
My child component generates form tags dynamycally - inputs,selects, textarea.
That means i can't have fixed styles in my css in my component for my content.
So when when the background page is white - i have one style for my inputs - for example black background. When the background page is black i have another style for my inputs - for example white bacgrkound.
To solve this is issue:
i tried
Adding input property in my child component ts file
#Input()
public cssTemplate;
in html
<div [ngClass]="{'form-group-white-bg': cssTemplate == 'white', 'form-group-dark-bg': cssTemplate == 'black'}">
<label for=""></label>
....
In the CHILD component i am sending value for input property depending on where the child component is called
if it is called on page with white background
<app-form-group cssTemplate="black" formControlName="address">
</app-form-group>
if it is called on black bacgrkound
<app-form-group cssTemplate="white" formControlName="address" [data]="{ field: 'address', label: 'Address' }">
</app-form-group>
but the problem here is that sometimes on my parent component this component is called multiply times
on one page can be called 12 times where i need 10 inputs and 2 selects
on other page can be called 15 times etc.
That means that i need to repat my self 15 times
<app-form-group cssTemplate="white" formControlName="address">
</app-form-group>
<app-form-group cssTemplate="white" formControlName="someItherControlName">
</app-form-group>
and everywhere to put cssTemplate="white".
ngFor is not an optin because this child component is called multiply times but not on same place in the HTML structure in the parent.
How can i solve this DRY?
you can add styles in your styles.css (the styles general for all the application). If e.g. you has
.white h1{
color:red;
}
.black h1{
color:green;
}
You can use [ngClass] in the "parent"
<div [ngClass]="toogle?'white':'black'">
<hello name="{{ name }}"></hello>
</div>
<button (click)="toogle=!toogle">toogle</button>
See [stackblitz][1]
NOTE: I used the way [ngClass]="expresion" (where expresion use conditional operator) better that [ngClass]="{'classname1':condition;'classname2':!condition}"
Update about your comment "how can i prevent repeating my self on child call", really I don't understand so much. I don't know if you want to make a directive like, e.g.
#Directive({
selector: 'hello', //<--the selector is the selector of the component
exportAs: 'helloDiv'
})
export class HelloDirective implements OnInit{
constructor(#Self() private component:HelloComponent,private dataService:DataService){
}
ngOnInit(){
console.log(this.component.name)
this.dataService.theme.subscribe(res=>{
this.component.theme=res;
})
}
}
This allow to "extends" the component -in the stackblitz the variable "theme" change-
[1]: https://stackblitz.com/edit/angular-ivy-sjwxyq?file=src%2Fapp%2Fapp.component.html
You can use an input property to create a css class map to pass on to ngClass. This object should be an object of string arrays.
It can be pretty much as complex and contain as many classes and rules as you need it too
#Input() color: 'white' | 'red' | 'hotpink' = 'white';
classMap: any;
ngOnInit() {
this.updateClassMap();
}
updateClassMap() {
this.classMap = {
[this.color]: !!this.color, // Add this class if not null
};
}
Then in the Html simply pass it to ngClass
<div [ngClass]="classMap">
Styling Child Components depending on Parent Component
There are two approaches I commonly take in this scenario
:ng-deep - create a style rule based on a class which is set in your parent component
utilize #ContentChildren() to set a property directly on your child components and call detectChanges() manually after the change.
To adopt the first solution you need to exercise greater care in your css naming rules, as using ng-deep obviously breaks the isolation of those style rules.
To adopt the second approach needs some considering due to it technically circumventing the standard input/output flow in Angular and thus can be a bit of a surprise "undocumented behavior" for any other maintainers of the application.
I'm a bit on the fence whether I prefer one approach over the other. The first approach seems more trivial to me, but it can also cause unintended style rule overwrites, while the second approach involves a lot more scripting and seems a bit of a hack.
Approach 1: ng-deep
Give your parent component an input and update a class on a block-element wrapping your <ng-content>.
create your desired style rules in your child component.
// parent component
#Component(...)
export class FooParent {
#Input() bgStyle: 'light' | 'dark' = 'light';
}
<!-- parent component template -->
<div class="parent" [ngClass]="{light: bgStyle == 'light', dark: bgStyle == 'dark'}">
<ng-content></ng-content>
</div>
// child.css
::ng-deep .light .child-container {
background-color: lightblue;
}
::ng-deep .dark .child-container {
background-color: royalblue;
}
My targeted element in the example is .child-container, you would write a similar style rule for each element you want to affect.
Approach 2: Using ContentChildren to pass along a value
Add a #ContentChildren() decorator to your parent component which selects for your child components.
inject a ChangeDetectorRef
implement ngAfterViewInit to loop through each child and set the value
call detectChanges() once done.
add the ngClass directive as normally in your child component.
Parent
#Component({
selector: 'parent',
templateUrl: 'parent.component.html',
styleUrls: ['parent.component.scss']
})
export class ParentComponent implements AfterViewInit, OnChanges {
#Input() bgStyle: 'light' | 'dark' = 'light';
#ContentChildren(ChildComponent) childComponents!: QueryList<ChildComponent>;
constructor(private change: ChangeDetectorRef) {
}
ngOnChanges(changes: SimpleChanges) {
if ('bgStyle' in changes) {
this.updateChildComponents();
}
}
updateChildComponents() {
this.childComponents.forEach(child => {
child.bgStyle = this.bgStyle;
});
this.change.detectChanges();
}
ngAfterViewInit() {
this.updateChildComponents();
}
}
<!-- parent.component.html -->
<ng-content></ng-content>
Child
#Component({
selector: 'child',
templateUrl: 'child.component.html',
styleUrls: ['child.component.scss']
})
export class ChildComponent implements OnInit {
bgStyle: 'light' | 'dark' = 'light';
constructor() {
}
ngOnInit(): void {
}
}
<!-- child.component.html -->
<div [ngClass]="{light: bgStyle == 'light', dark: bgStyle == 'dark'}" class="child-container"></div>
// child.component.css - you would apply styles as you needed obviously.
.child-container {
width: 40px;
height: 40px;
margin: .5rem;
}
.light.child-container {
background-color: lightblue;
}
.dark.child-container {
background-color: royalblue;
}
Usage
<!-- any other template -->
<parent>
<child></child>
<child></child>
<child></child>
</parent>
Note: If you are creating the ChildComponent directly in the ParentComponent's own template you need to use #ViewChildren instead of #ContentChildren

How to access local css class names from within the angular component

I need to access the generated css classname from within an angular component, in order to style a 3rd-party component.
Angular does some magic transformations on the local css classnames to enable scoping. I need to apply some custom styles to an ngx-datatable component. To do this, I need to pass it custom classnames. Because of what angular does to the classnames, these no longer match.
Adding the classnames to the global scope or using ::ng-deep both work, however I would rather not break the encapsulation.
dashboard-component.ts
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent {
getRowClass(row){
return 'my-class';
}
}
dashboard-component.scss
.my-class {
background: green;
}
dashboard-component.html
<ngx-datatable
[rowclass]="getRowClass"
></ngx-datatable>
The way I see it I should be able to access some reference to the css class from within the component, say this._styles, which will then carry the generated name of the class at runtime, so I can do
getRowClass(row){
return this._styles['my-class'];
}
I think you are not able to propagate your styles to ngx-datatable.
You can use encapsulation: ViewEncapsulation.None within your #component but make sure you use it carefully as it will lead to some weird css behaviours.
Next, What you can do is create a container for your dashboard.html file like:
<div class="dashboard-container">
<ngx-datatable></ngx-datatable>
</div>
and inside your dashboard.scss you can reference the parent container
.dashboard-container {
.my-style{}
}
Just put the css classes in the global style file ,otherwise you will need to use ::ng-deep,so my advice to put ngx-datatable in the global style file
check the ngx-datatable demo asset/app.css where the did the same
another option you can set the encapsulation: ViewEncapsulation.None on the component the the class name will be the same
#Component({
selector: "app-demo",
templateUrl: "./demo.component.html",
styleUrls: ["./demo.component.scss"],
encapsulation:ViewEncapsulation.None
})
export class DemoComponent implements OnInit {
demo.component.scss
ngx-datatable {
.green-color {
background:green;
& div {
color :#fff;
}
}
}
set the encapsulation to none or put the style in global style file are the same here because both ways will be the style globally without any change
demo 🔥

Prevent global CSS being applied a component in Angular 5

In .angular-cli.json, I got some global styles:
"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.css",
"../node_modules/font-awesome/css/font-awesome.css",
"../node_modules/ng2-toastr/bundles/ng2-toastr.min.css",
"styles.scss"
],
But I don't want any of them being applied to a specific component - is it achievable?
EDIT 1:
Unfortunately, overriding the CSS style in the component style won't work because the HTML in the template of the component is fetched from a Web API backend - I guess I can't realistically override every possible class/selector?
CSS cascades (hence the term, Cascading Style Sheets).
for full browser support your only option is to override selectors.
another option, not as common due to lack of support on IE and Edge,
is the all property.
html
<div class="component-container">
<!-- your components html template ... -->
</div>
css
.component-container {
all: initial;
all: unset;
}
Using component styles
For every Angular component you write, you may define not only an HTML template, but also the CSS styles that go with that template, specifying any selectors, rules, and media queries that you need.
One way to do this is to set the styles property in the component metadata. The styles property takes an array of strings that contain CSS code. Usually you give it one string, as in the following example:
#Component({
selector: 'app-root',
template: `
<h1>Test Text</h1>
`,
styles: ['h1 { font-weight: normal; }']
})
export class AppComponent {
/* . . . */
}
styleUrls
One or more URLs for files containing CSS stylesheets to use in this component.
styleUrls: string[]
styles
One or more inline CSS stylesheets to use in this component.
styles: string[]
You can use the :not selector in your global CSS.
You'd have to play around with it to get the desired behaviour but it should be something like this:
h1:not(.my-specific-class) {
font-size: 3rem;
}
You can use angular built in shadowDom API from view encapsulation. Which will make your component elements loaded inside a separate DOM tree so global css wont affect your component elements.
#Component({
selector: 'app-root',
template: `
<h1 class="head-app">Test Heading</h1>
`,
styles: ['./app.component.scss'],
encapsulation: ViewEncapsulation.ShadowDom
})
export class AppComponent {
/* . . .
You can define styles at component level using styleUrls property inside the scope of #Component. Please have a look at below code:-
#Component({
selector: 'app-manageUser',
templateUrl: './manageUser.component.html',
styleUrls: ['./manageUser.component.css'],
providers: [UserService]
})

Custom Styling of mdToolTip

I have the following code in an Angular project
<input class="form-control" type="number" [(ngModel)]="cons.failPercent" [ngModelOptions]="{standalone: true}"
mdTooltip="Typically valves can be repaired three times before they need to be replaced"
mdTooltipPosition="right"
autofocus/>
In my component I have
#Component({
templateUrl: './ownership-form.component.html',
styleUrls: ['./ownership-form.component.css'],
encapsulation: ViewEncapsulation.None
})
and in my CSS I have
.md-tooltip{
color:yellow !important;
height:auto;
}
But it does not appear to be styling the tooltip. How can I fix this?
Depending on your Angular version you'll need to use the /deep/ or ::ng-deep combination selectors to circumvent encapsulation. Alternatively, set the styling on your global stylesheet (commonly styles.scss).
Angular 2:
/deep/ .md-tooltip { ... }
Angular 4.3+:
::ng-deep .md-tooltip { ... }
More info at Hackernoon
I would personally scope your styles to the component in question.
Angular < v4.2
:host /deep/ {
.md-tooltip { ... }
}
:host >>> {
.md-tooltip { ... }
}
Angular >= v4.2
:host ::ng-deep {
.md-tooltip { ... }
}
If you remove your encapsulation from the component. The styles should still work. By adding ::ng-deep inside the :host(..) it will emulate global css. But only in a downward piercing direction.
Angular is trying to promote component level styles. I would avoid moving code to the global stylesheets. If you visit a route which does not require the component in question then you are instantiating (loading code) for no reason.

Angular 2: Styling router-outlet to have width < 100%

I'm building an Angular 2 app which would have a side nav bar for screens wider than 500, and a bottom nav bar for screens less wide than 500. For now I was trying to assign a 20% width to the side bar, 80% to app content.
The problem that I have is that the router-outlet content (i.e. the actual app) takes up the full width of the page instead of just 80%. It seems to be ignoring any styling I try to give it. Are we not supposed to style router-outlet directly? Or perhaps there is a better way that I'm overlooking?
app.component.ts
import { Component, HostListener } from '#angular/core';
#Component({
selector: 'my-app',
template: `
<div class="container-fluid">
<nav *ngIf="this.window.innerWidth > 500"></nav>
<router-outlet style="width:80%;float:right;"></router-outlet>
<nav *ngIf="this.window.innerWidth < 500"></nav>
`,
styleUrls: ['app/app.component.css']
})
export class AppComponent {
window = [];
ngOnInit(): void {
this.window.innerWidth = window.innerWidth;
}
#HostListener('window:resize', ['$event'])
onResize(event) {
this.window.innerWidth = event.target.innerWidth;
console.log(this.window.innerWidth);
}
}
Simple solution is to just put <router-outlet> in a styled div:
<div style="width:80%;float:right;">
<router-outlet></router-outlet>
</div>
By using :host we can modify the style while loading the component.
:host(selector) { width:70% }
Following is the component:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'test-selector',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent{
}
//test.component.css content
:host(test-selector) { width:70% } will reduce the width to 70%
The key is /deep/ keyword:
:host /deep/ router-outlet + *:not(nav) {
width:80%;
float:right;
}
Since the component is dynamically loaded right after tag, the selector '+' matches anything next to it.
And the :not() selector excludes element in your template.
Edited 2018/3/1:
Since Angular 4.3.0 made /deep/ deprecated, its suggested alternative is ::ng-deep. And there were a long discussion about this.
Use host:{'style':'width:70%'} within #Component({}) in the component file to set the width of child
you could do the same with css grid. as width the accepted answer, it seems to only work in a surrounding div

Resources