Coder Social home page Coder Social logo

angular2's Introduction

Angular2

Service Workers

Angular Mobile Toolkit

Angular CLI

<ng-container>

The Angular <ng-container> is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.

<p>
  I turned the corner
  <ng-container *ngIf="hero">
    and saw {{hero.name}}. I waved
  </ng-container>
  and continued on my way.
</p>

<ng-content>

The <ng-content> tag is a placeholder for the external content. It tells Angular where to insert that content.

// Using the component
<foo-bar>
  <div class='project-class'>
    ProjectClass
  </div>

  <div>
    ProjectedElement
  </div>

  <div projectAttr>
    ProjectAttr
  </div>
 </foo-bar>
// Component template
<ng-content select=".project-class"> </ng-content>
<ng-content select="[projectAttr]"> </ng-content>
<ng-content select="div"> </ng-content>

Angular2 - catch/subscribe to (click) event in dynamically added HTML

Declarative event binding is only supported in static HTML in a components template. If you want to subscribe to events of elements dynamically added, you need to do it imperatively.

elementRef.nativeElement.querySelector(...).addEventListener(...)

or similar.

If you want to be WebWorker-safe, you can inject the Renderer

constructor(private elementRef:ElementRef, private renderer:Renderer) {}

and use instead

this.renderer.listen(this.elementRef.nativeElement, 'click', (event) => { handleClick(event);});

to register an event handler.

You can use listenGlobal that will give you access to document, body, etc.

this.renderer.listenGlobal('document', 'click', (event) => {
  // Do something with 'event'
});

Note that since beta.2 both listen and listenGlobal return a function to remove the listener. This is to avoid memory leaks in big applications.

// listenFunc will hold the function returned by "renderer.listen"
listenFunc: Function;

// globalListenFunc will hold the function returned by "renderer.listenGlobal"
globalListenFunc: Function;

constructor(elementRef: ElementRef, renderer: Renderer) {

    // We cache the function "listen" returns
    this.listenFunc = renderer.listen(elementRef.nativeElement, 'click', (event) => {
        // Do something with 'event'
    });

    // We cache the function "listenGlobal" returns
    this.globalListenFunc = renderer.listenGlobal('document', 'click', (event) => {
        // Do something with 'event'
    });
}

ngOnDestroy() {
    // We execute both functions to remove the respectives listeners

    // Removes "listen" listener
    this.listenFunc();

    // Removs "listenGlobal" listener
    this.globalListenFunc();
}

takeWhile()

The TakeWhile mirrors the source Observable until such time as some condition you specify becomes false, at which point TakeWhile stops mirroring the source Observable and terminates its own Observable.

First, we need to import the takeWhile() operator:

import "rxjs/add/operator/takeWhile";

Then, let’s use the takeWhile() operator with our observable that is returned from UserService.authenticate():

export class MyComponent implements OnDestroy, OnInit {

  public user: User;
  private alive: boolean = true;

  public ngOnInit() {
    this.userService.authenticate(email, password)
      .takeWhile(() => this.alive)
      .subscribe(user => {
        this.user = user;
      });
  }

  public ngOnDestroy() {
    this.alive = false;
  }

}

First, I defined a private boolean variable named alive that is set to true. Next, we provide a function to the takeWhile() operator that returns the boolean value (that is initially true). Finally, we set the value of alive to false when the component is destroyed.

As you can see, the takeWhile() operator is an excellent solution to unsubscribing from an observable subscription as part of Angular’s component lifecycle.

Observable

import { Observable } from 'rxjs/Observable'

test(val): Observable<any> {
    return new Observable((observable) => {
        if(val) {
            observable.next('success');
        } else {
            observable.error('error');
        }
    });
}

this.test(false)
    .subscribe(
        (success) => {
            console.log(success);
        },
        (error) => {
            console.log(error);
        }
    );

Don't forget to unsubscribe() or takeWhile()

Promise

test(val): Promise<any> {
      return new Promise((resolve, reject) => {
          if(val) {
              resolve('success');
          } else {
              reject('error');
          }
      });
  }
  
this.test(false)
    .then(
        (success) => {
            console.log(success);
        },
        (error) => {
            console.log(error);
        }
    );

angular2's People

Contributors

blah2014 avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.