简体   繁体   中英

Is it possible to use [ngClass] on an app component where the class is inside the component for Angular 6?

I have an angular 6 app and I am trying to apply another CSS class to one of my app components in the app.component.html file. Basically, I want to change the color of the footer of my app based on a condition, and all other cases don't show the footer. So, my code looks like this:

app.component.html

<router-outlet></router-outlet>
<my-footer [ngClass]="{ 'my-class' : true }"></my-footer>

my-footer.css

:host {
    background-color: black;
    color: white;
}

.my-class {
    background-color: red;
}

Is it possible to use [ngClass] this way, where the class exists in the component I am applying the condition to itself? I found if I put .my-class in the app.component.css file, then it works as expected. However, I want to keep my styles together in the components where they belong.

Thanks!

Keep your component style inside the component. You want to change your approach to:

<my-footer *ngIf="ifMyCondition === true"></my-footer>

In this case, It will only construct the footer if your condition is true.

UPDATE--
As you mentioned in your comment, I still suggest you to handle components needs inside the component and not rely on outsource (in your case the parent?) to change the component properties. So I will suggest you to use Input() in your child to get the status of your condition from your parent, and then handle it how ever you want.

Parent:

someCondition: boolean;

HTML :

<my-footer [condition]="someCondition"></my-footer>


Child:

@Input() condition: boolean;


And now, each time your condition changed in your parent, The bind with the child will keep update him so you can manage what ever you need in you child component based on the condition that bind in the parent.

Using the selector :host.my-class appears to work, as shown in this stackblitz .

my-footer.css

:host {
    background-color: black;
    color: white;
}

:host.my-class {
    background-color: red;
}

app.component.html

<my-footer [ngClass]="{ 'my-class' : condition }"></my-footer>

You can apply your class based on a condtition.

You can do something like this:

app.component.html

<router-outlet></router-outlet>
<my-footer [ngClass]="{ 'my-class' : displayFooterBg() }"></my-footer>

app.component.ts

displayFooterBg = () => {
  if (this.condition === true) {
    return true;
  } else {
    return false;
  }
}

You can give the class as an input to the child component.

Parent (HTML):

<my-footer [classValue]="class1"></my-footer>

Child (TS):

@Input() public classValue = 'default-class';

Child (HTML)

<div ngClass = {{classValue }}></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM