Skip to content

Instantly share code, notes, and snippets.

@manoharlk
Last active December 3, 2016 09:05
Show Gist options
  • Select an option

  • Save manoharlk/59ab5124c1af9b8638b1041708b07202 to your computer and use it in GitHub Desktop.

Select an option

Save manoharlk/59ab5124c1af9b8638b1041708b07202 to your computer and use it in GitHub Desktop.
NG2

Adding and removing classes in angular

  • directly binding with [style.background-color]
  • adding a class [class.my-class]
  • using NgClass [ngClass]
  • by directly accessing the native DOM element
<div  [class.nameOfClass]="Expression resulting true or false">
</div>
<div [style.background-color]="getStyle()">//="'orange'"
        I am a div that wants to be styled
</div>
<div [className]="'blue'">CSS class using property syntax, this text is blue</div>
<div [ngStyle]="{'color': 'blue', 'font-size': '24px', 'font-weight': 'bold'}">
  style using ngStyle
</div>
 <div [ngClass]="{'my-class': isClassVisible }">
        I am a div that wants to be styled
 </div>
<div [ngClass]="['bold-text', 'green']">array of classes</div>
<div [ngClass]="'italic-text blue'">string of classes</div>
<div [ngClass]="{'small-text': true, 'red': true}">object of classes</div>

<button (click)="isClassVisible = !isClassVisible;">Toggle style</button> 
<div styled>
    I'm a div that wants to be styled
</div>
    
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');
  }
}

ElementRef provides access to the underlying native element(DOM Node).

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. Thus, the Renderer provides an abstraction over the native elements.

Using HostBinding- adding class to host element

@Component({
   selector: 'body',
   host:     {'[class.someClass]':'someField'}
})
export class AppElement implements AfterViewInit {
  someField: bool = false;
  // alternatively to the host parameter in `@Component`
  // @HostBinding('class.someClass') someField: bool = false;

  ngAfterViewInit() {
    someField = true; // set class `someClass` on `<body>`
  }
}

DOM traversing in angular2

  • Child components in our view can be accessed from our parent component easily with @ViewChild

    import { Component, ViewChild } from '@angular/core';
    import { UserProfile } from '../user-profile';
    
    @Component({
      template: '<user-profile (click)="update()"></user-profile>',
    })
    export class MasterPage {
      // ViewChild takes a class type or a reference name string.
      // Here we are using the type
      @ViewChild(UserProfile) userProfile: UserProfile
      constructor() { }
      ngAfterViewInit() {
        // After the view is initialized, this.userProfile will be available
        this.update();
      }
      update() {
        this.userProfile.sendData();
      }
    }

    local variable instead of loading the particular class

    import { Component, ViewChild } from '@angular/core';
    import { UserProfile } from '../user-profile';
    
    @Component({
      template: '<user-profile #myProfile (click)="update()"></user-profile>'
    })
    export class MasterPage {
      @ViewChild('myProfile') userProfile: UserProfile
      constructor() { }
      update(){
        this.userProfile.sendData();
      }
    }

ElementHref

provides access to the underlying native element

Checkbox hack instead of multiple ngclicks

import{Component} from '@angular/core';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';
@Component({ 
    selector:'mv-menu1',
    template:`
    <button (click)="select()">Clock</button>
    <div class="form-group">
    <label for="options">Options:</label>
    <div *ngFor="let option of options">
        <label>
            <input type="checkbox"
                   name="options"
                   value="{{option.value}}"
                   [(ngModel)]="option.checked"/>
            {{option.name}}
        </label>
    </div>
</div>
    `
})

export class MyComponent {
  options = [
    {name:'OptionA', value:'1', checked:true},
    {name:'OptionB', value:'2', checked:false},
    {name:'OptionC', value:'3', checked:true}
  ]
  select() { 
      console.log(this.options
              .filter(opt => opt.checked)
              .map(opt => opt.value));
      // right now: ['1','3']
    return this.options
              .filter(opt => opt.checked)
              .map(opt => opt.value);
  }
}

Availability of mouseover events

Angular2 supports all events the browser fires 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment