2

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.

1
  • share your template from footer.component.html Commented Dec 21, 2016 at 5:37

5 Answers 5

6

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'}
})
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

2

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(){};
  ...
}

From official documentation

Comments

1

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.

Comments

0

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');
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.