Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add class attribute in angular 2 component typescript file?

Tags:

angular

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.

like image 739
Kapil Yadav Avatar asked May 31 '26 12:05

Kapil Yadav


2 Answers

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'}
})
like image 114
user5198302 Avatar answered Jun 02 '26 00:06

user5198302


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.

like image 32
Vinay Pandya Avatar answered Jun 02 '26 00:06

Vinay Pandya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!