Reputation: 706
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.
Upvotes: 2
Views: 12799
Reputation: 159
On Angular v7+ it is recommended to use HostBinding
to achieve this.
import { HostBinding } from '@angular/core';
export class FooterComponent implements OnInit {
@HostBinding('class') class = 'my-footer';
constructor(){};
...
}
Upvotes: 2
Reputation: 61
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'}
})
Upvotes: 6
Reputation: 3150
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.
Upvotes: 3
Reputation: 13558
You need to assign Footer
type to variable of your component :
import { Component } from '@angular/core';
import { Footer } from './footer';
@Component({
moduleId: module.id,
selector: 'footer',
templateUrl: 'footer.component.html'
})
export class FooterComponent {
public footerClass: Footer;
constructor() {
this.footerClass = new Footer('Footer Content');
}
}
Upvotes: 0
Reputation: 1066
First make your variable css_class
a public property of your component
Then, in your template footer.component.html, just interpolate your variable css_class
as follow:
<div class='{{css_class}}'>test</div>
This is just an example the important part is the class
attribute and its value.
Upvotes: 1