Conditionally add styles to an element

Here we're going through a couple of ways to conditionally apply some styles to a DOM element in Angular 2.

Directly manipulating styles property

A rather unconventional way would be to return the styling property as a string and then to directly set it on the desired element:

//our root app component
import {Component} from '@angular/core'

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <div [style.background-color]="getStyle()">
        I am a div that wants to be styled
      </div>
      <button (click)="showStyle = !showStyle;">Toggle style</button>
    </div>
  `,
  directives: []
})
export class App {
  showStyle: false;
  
  constructor() {
  }
  
  getStyle() {
    if(this.showStyle){
      return "yellow";
    } else {
      return "";
    }
  }
}

Note the [style.background-color] in the code above.

Adding a class

Similarly as we did with the background-color above, we can add a class, using the following notation: [class.nameOfClass]="someCondition".

//our root app component
import {Component} from '@angular/core'

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <div [class.my-class]="isClassVisible">
        I am a div that wants to be styled
      </div>
      <button (click)="isClassVisible = !isClassVisible;">Toggle style</button>
    </div>
  `,
  styles: [
  `
  .my-class {
    background-color: yellow;
  }
  `
  ]
  directives: []
})
export class App {
  isClassVisible: false;
  
  constructor() {
  }
  
}

The good old “ngClass”

Theres another way of adding a class. Especially Angular 1 developers may immediately recognize this. The good old NgClass.

It is made available under the @angular/common module which is imported already for you, so there’s no need to do it manually. Then we can use it just as we did in Angular 1. Here’s the full code example.

//our root app component
import {Component} from '@angular/core';

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <div [ngClass]="{'my-class': isClassVisible }">
        I am a div that wants to be styled
      </div>
      <button (click)="isClassVisible = !isClassVisible;">Toggle style</button>
    </div>
  `,
  styles: [
  `
  .my-class {
    background-color: yellow;
  }
  `
  ]
})
export class App {
  isClassVisible: false;
  
  constructor() {
  }
  
}

Referencing the DOM element directly via ElementRef

The last possibility is by directly interacting with the underlying DOM element. For that purpose we create a directive styled which we add to our div.

<div styled>
    I'm a div that wants to be styled
</div>

Our directive looks like this:

import {Directive, ElementRef, Renderer} from '@angular/core';

@Directive({
  selector: '[styled]',
})
export class StyledDirective {
  constructor(public el: ElementRef, public renderer: Renderer) {
    // el.nativeElement.style.backgroundColor = 'yellow';
    renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'yellow');
  }
}

The important part here is the ElementRef and the Renderer which I import in the constructor.

The ElementRef allows us to gain access to the nativeElement API via

el.nativeElement.style.backgroundColor = 'yellow';

This way you can deliberately modify the properties of the native DOM element. So why would I want to use the Renderer. Well, Angular 2 isn’t only build for the browser, but it can potentially also be rendered on the server or render native elements on a mobile device (via NativeScript for instance). Thus, the Renderer provides an abstraction over the native elements.

Check out this Plunk for the full code.

Conclusion

So in this article you learned about three possibilities to style your DOM elements from within Angular 2. You got to see

  • directly binding with [style.background-color]
  • adding a class [class.my-class]
  • using NgClass [ngClass]
  • by directly accessing the native DOM element

You even quickly saw how to create a Directive and how to embed styles within a Component :smiley:.

原文链接:http://juristr.com/blog/2016/01/learning-ng2-dynamic-styles/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值