How to add class attribute in angular 2 component typescript file ?
Below is my footer component code, i want to add footer class to it.
footer.component.ts
import { Component } from '@angular/core';
import { Footer } from './footer';
@Component({
moduleId: module.id,
selector: 'footer',
templateUrl: 'footer.component.html'
})
export class FooterComponent {
constructor() {
this.title = 'Footer Content';
this.css_class = 'navbar-fixed-bottom';
}
}
footer.ts
export class Footer {
constructor(
public title: string
) { }
}
Please suggest.
You can use the host metadata property of the Component decorator.
https://angular.io/docs/ts/latest/api/core/index/Component-decorator.html
Your Component decorator should look like this:
@Component({
moduleId: module.id,
selector: 'footer',
templateUrl: 'footer.component.html',
host: {'class': 'my-footer'}
})
There are several ways to do add CSS class to your HTML.
first is that
<div class='{{css_class}}'>...</div>
and second is you can add CSS class based on some conditions/flag, CSS class will be added to dom when a condition is true.
export class FooterComponent {
let addCssClass : boolean = true;
constructor() {
this.title = 'Footer Content';
this.css_class = 'navbar-fixed-bottom';
}
}
in you HTML <div [class.navbar-fixed-bottom]="addCssClass">...</div> when ever addCssClass is true navbar-fixed-bottom will added to the div.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With