Welcome to Knowledge Base!

KB at your finger tips

Book a Meeting to Avail the Services of Angular overtime

This is one stop global knowledge base where you can learn about all the products, solutions and support features.

Categories
All

Angular

Angular - Observables compared to other techniques

Observables compared to other techniques link

You can often use observables instead of promises to deliver values asynchronously. Similarly, observables can take the place of event handlers. Finally, because observables deliver multiple values, you can use them where you might otherwise build and operate on arrays.

Observables behave somewhat differently from the alternative techniques in each of these situations, but offer some significant advantages. Here are detailed comparisons of the differences.

Observables compared to promises link

Observables are often compared to promises. Here are some key differences:

  • Observables are declarative; computation does not start until subscription. Promises execute immediately on creation. This makes observables useful for defining recipes that can be run whenever you need the result.

  • Observables provide many values. Promises provide one. This makes observables useful for getting multiple values over time.

  • Observables differentiate between chaining and subscription. Promises only have .then() clauses. This makes observables useful for creating complex transformation recipes to be used by other part of the system, without causing the work to be executed.

  • Observables subscribe() is responsible for handling errors. Promises push errors to the child promises. This makes observables useful for centralized and predictable error handling.

Creation and subscription link

  • Observables are not executed until a consumer subscribes. The subscribe() executes the defined behavior once, and it can be called again. Each subscription has its own computation. Resubscription causes recomputation of values.

    src/observables.ts (observable)
          
          // declare a publishing operation
    const observable = new Observable<number>(observer => {
      // Subscriber fn...
    });
    
    // initiate execution
    observable.subscribe(value => {
      // observer handles notifications
    });
        
  • Promises execute immediately, and just once. The computation of the result is initiated when the promise is created. There is no way to restart work. All then clauses (subscriptions) share the same computation.

    src/promises.ts (promise)
          
          // initiate execution
    let promise = new Promise<number>(resolve => {
      // Executer fn...
    });
    promise.then(value => {
      // handle result here
    });
        

Chaining link

  • Observables differentiate between transformation function such as a map and subscription. Only subscription activates the subscriber function to start computing the values.

    src/observables.ts (chain)
          
          observable.pipe(map(v => 2 * v));
        
  • Promises do not differentiate between the last .then clauses (equivalent to subscription) and intermediate .then clauses (equivalent to map).

    src/promises.ts (chain)
          
          promise.then(v => 2 * v);
        

Cancellation link

  • Observable subscriptions are cancellable. Unsubscribing removes the listener from receiving further values, and notifies the subscriber function to cancel work.

    src/observables.ts (unsubscribe)
          
          const subscription = observable.subscribe(() => {
      // observer handles notifications
    });
    
    subscription.unsubscribe();
        
  • Promises are not cancellable.

Error handling link

  • Observable execution errors are delivered to the subscriber's error handler, and the subscriber automatically unsubscribes from the observable.

    src/observables.ts (error)
          
          observable.subscribe(() => {
      throw new Error('my error');
    });
        
  • Promises push errors to the child promises.

    src/promises.ts (error)
          
          promise.then(() => {
      throw new Error('my error');
    });
        

Cheat sheet link

The following code snippets illustrate how the same kind of operation is defined using observables and promises.

Operation Observable Promise
Creation
      
      new Observable((observer) => { 
  observer.next(123); 
});
    
      
      new Promise((resolve, reject) => { 
  resolve(123); 
});
    
Transform
      
      obs.pipe(map((value) => value * 2));
    
      
      promise.then((value) => value * 2);
    
Subscribe
      
      sub = obs.subscribe((value) => { 
  console.log(value) 
});
    
      
      promise.then((value) => { 
  console.log(value); 
});
    
Unsubscribe
      
      sub.unsubscribe();
    
Implied by promise resolution.

Observables compared to events API link

Observables are very similar to event handlers that use the events API. Both techniques define notification handlers, and use them to process multiple values delivered over time. Subscribing to an observable is equivalent to adding an event listener. One significant difference is that you can configure an observable to transform an event before passing the event to the handler.

Using observables to handle events and asynchronous operations can have the advantage of greater consistency in contexts such as HTTP requests.

Here are some code samples that illustrate how the same kind of operation is defined using observables and the events API.

Observable Events API
Creation & cancellation
      
      // Setup 
const clicks$ = fromEvent(buttonEl, 'click'); 
// Begin listening 
const subscription = clicks$ 
  .subscribe(e => console.log('Clicked', e)) 
// Stop listening 
subscription.unsubscribe();
    
      
      function handler(e) { 
  console.log('Clicked', e); 
} 
// Setup & begin listening 
button.addEventListener('click', handler); 
// Stop listening 
button.removeEventListener('click', handler);
    
Subscription
      
      observable.subscribe(() => { 
  // notification handlers here 
});
    
      
      element.addEventListener(eventName, (event) => { 
  // notification handler here 
});
    
Configuration Listen for keystrokes, but provide a stream representing the value in the input.
      
      fromEvent(inputEl, 'keydown').pipe( 
  map(e => e.target.value) 
);
    
Does not support configuration.
      
      element.addEventListener(eventName, (event) => { 
  // Cannot change the passed Event into another 
  // value before it gets to the handler 
});
    

Observables compared to arrays link

An observable produces values over time. An array is created as a static set of values. In a sense, observables are asynchronous where arrays are synchronous. In the following examples, implies asynchronous value delivery.

Values Observable Array
Given
      
      obs: 12357
    
      
      obsB: 'a''b''c'
    
      
      arr: [1, 2, 3, 5, 7]
    
      
      arrB: ['a', 'b', 'c']
    
concat()
      
      concat(obs, obsB)
    
      
      12357'a''b''c'
    
      
      arr.concat(arrB)
    
      
      [1,2,3,5,7,'a','b','c']
    
filter()
      
      obs.pipe(filter((v) => v>3))
    
      
      57
    
      
      arr.filter((v) => v>3)
    
      
      [5, 7]
    
find()
      
      obs.pipe(find((v) => v>3))
    
      
      5
    
      
      arr.find((v) => v>3)
    
      
      5
    
findIndex()
      
      obs.pipe(findIndex((v) => v>3))
    
      
      3
    
      
      arr.findIndex((v) => v>3)
    
      
      3
    
forEach()
      
      obs.pipe(tap((v) => { 
  console.log(v); 
})) 
1 
2 
3 
5 
7
    
      
      arr.forEach((v) => { 
  console.log(v); 
}) 
1 
2 
3 
5 
7
    
map()
      
      obs.pipe(map((v) => -v))
    
      
      →-1→-2→-3→-5→-7
    
      
      arr.map((v) => -v)
    
      
      [-1, -2, -3, -5, -7]
    
reduce()
      
      obs.pipe(reduce((s,v)=> s+v, 0))
    
      
      18
    
      
      arr.reduce((s,v) => s+v, 0)
    
      
      18
    
Last reviewed on Mon Feb 28 2022

Stay Ahead in Today’s Competitive Market!
Unlock your company’s full potential with a Virtual Delivery Center (VDC). Gain specialized expertise, drive seamless operations, and scale effortlessly for long-term success.

Book a Meeting to Avail the Services of Angularovertime

Angular

link

Last reviewed on Mon Aug 22 2022
Read article

Angular

link

Last reviewed on Mon Aug 22 2022
Read article

Angular

link

Last reviewed on Mon Aug 22 2022
Read article

Angular

link

Last reviewed on Mon Aug 22 2022
Read article

Angular - Complex animation sequences

Complex animation sequences link

Prerequisites link

A basic understanding of the following concepts:

  • Introduction to Angular animations
  • Transition and triggers

So far, we've learned simple animations of single HTML elements. Angular also lets you animate coordinated sequences, such as an entire grid or list of elements as they enter and leave a page. You can choose to run multiple animations in parallel, or run discrete animations sequentially, one following another.

The functions that control complex animation sequences are:

Functions Details
query() Finds one or more inner HTML elements.
stagger() Applies a cascading delay to animations for multiple elements.
group() Runs multiple animation steps in parallel.
sequence() Runs animation steps one after another.

The query() function link

Most complex animations rely on the query() function to find child elements and apply animations to them, basic examples of such are:

Examples Details
query() followed by animate() Used to query simple HTML elements and directly apply animations to them.
query() followed by animateChild() Used to query child elements, which themselves have animations metadata applied to them and trigger such animation (which would be otherwise be blocked by the current/parent element's animation).

The first argument of query() is a css selector string which can also contain the following Angular-specific tokens:

Tokens Details
:enter
:leave
For entering/leaving elements.
:animating For elements currently animating.
@*
@triggerName
For elements with any—or a specific—trigger.
:self The animating element itself.
Entering and Leaving Elements

Not all child elements are actually considered as entering/leaving; this can, at times, be counterintuitive and confusing. Please see the query api docs for more information.

You can also see an illustration of this in the animations live example (introduced in the animations introduction section) under the Querying tab.

Animate multiple elements using query() and stagger() functions link

After having queried child elements via query() , the stagger() function lets you define a timing gap between each queried item that is animated and thus animates elements with a delay between them.

The following example demonstrates how to use the query() and stagger() functions to animate a list (of heroes) adding each in sequence, with a slight delay, from top to bottom.

  • Use query() to look for an element entering the page that meets certain criteria

  • For each of these elements, use style() to set the same initial style for the element. Make it transparent and use transform to move it out of position so that it can slide into place.

  • Use stagger() to delay each animation by 30 milliseconds

  • Animate each element on screen for 0.5 seconds using a custom-defined easing curve, simultaneously fading it in and un-transforming it

src/app/hero-list-page.component.ts
      
      animations: [
  trigger('pageAnimations', [
    transition(':enter', [
      query('.hero', [
        style({opacity: 0, transform: 'translateY(-100px)'}),
        stagger(30, [
          animate('500ms cubic-bezier(0.35, 0, 0.25, 1)',
          style({ opacity: 1, transform: 'none' }))
        ])
      ])
    ])
  ]),
    

Parallel animation using group() function link

You've seen how to add a delay between each successive animation. But you might also want to configure animations that happen in parallel. For example, you might want to animate two CSS properties of the same element but use a different easing function for each one. For this, you can use the animation group() function.

NOTE :
The group() function is used to group animation steps , rather than animated elements.

The following example uses group() s on both :enter and :leave for two different timing configurations, thus applying two independent animations to the same element in parallel.

src/app/hero-list-groups.component.ts (excerpt)
      
      animations: [
  trigger('flyInOut', [
    state('in', style({
      width: '*',
      transform: 'translateX(0)', opacity: 1
    })),
    transition(':enter', [
      style({ width: 10, transform: 'translateX(50px)', opacity: 0 }),
      group([
        animate('0.3s 0.1s ease', style({
          transform: 'translateX(0)',
          width: '*'
        })),
        animate('0.3s ease', style({
          opacity: 1
        }))
      ])
    ]),
    transition(':leave', [
      group([
        animate('0.3s ease', style({
          transform: 'translateX(50px)',
          width: 10
        })),
        animate('0.3s 0.2s ease', style({
          opacity: 0
        }))
      ])
    ])
  ])
]
    

Sequential vs. parallel animations link

Complex animations can have many things happening at once. But what if you want to create an animation involving several animations happening one after the other? Earlier you used group() to run multiple animations all at the same time, in parallel.

A second function called sequence() lets you run those same animations one after the other. Within sequence() , the animation steps consist of either style() or animate() function calls.

  • Use style() to apply the provided styling data immediately.
  • Use animate() to apply styling data over a given time interval.

Filter animation example link

Take a look at another animation on the live example page. Under the Filter/Stagger tab, enter some text into the Search Heroes text box, such as Magnet or tornado .

The filter works in real time as you type. Elements leave the page as you type each new letter and the filter gets progressively stricter. The heroes list gradually re-enters the page as you delete each letter in the filter box.

The HTML template contains a trigger called filterAnimation .

src/app/hero-list-page.component.html
      
      <label for="search">Search heroes: </label>
<input type="text" id="search" #criteria
       (input)="updateCriteria(criteria.value)"
       placeholder="Search heroes">

<ul class="heroes" [@filterAnimation]="heroesTotal">
  <li *ngFor="let hero of heroes" class="hero">
    <div class="inner">
      <span class="badge">{{ hero.id }}</span>
      <span class="name">{{ hero.name }}</span>
    </div>
  </li>
</ul>
    

The filterAnimation in the component's decorator contains three transitions.

src/app/hero-list-page.component.ts
      
      @Component({
  animations: [
    trigger('filterAnimation', [
      transition(':enter, * => 0, * => -1', []),
      transition(':increment', [
        query(':enter', [
          style({ opacity: 0, width: 0 }),
          stagger(50, [
            animate('300ms ease-out', style({ opacity: 1, width: '*' })),
          ]),
        ], { optional: true })
      ]),
      transition(':decrement', [
        query(':leave', [
          stagger(50, [
            animate('300ms ease-out', style({ opacity: 0, width: 0 })),
          ]),
        ])
      ]),
    ]),
  ]
})
export class HeroListPageComponent implements OnInit {
  heroesTotal = -1;

  get heroes() { return this._heroes; }
  private _heroes: Hero[] = [];

  ngOnInit() {
    this._heroes = HEROES;
  }

  updateCriteria(criteria: string) {
    criteria = criteria ? criteria.trim() : '';

    this._heroes = HEROES.filter(hero => hero.name.toLowerCase().includes(criteria.toLowerCase()));
    const newTotal = this.heroes.length;

    if (this.heroesTotal !== newTotal) {
      this.heroesTotal = newTotal;
    } else if (!criteria) {
      this.heroesTotal = -1;
    }
  }
}
    

The code in this example performs the following tasks:

  • Skips animations when the user first opens or navigates to this page (the filter animation narrows what is already there, so it only works on elements that already exist in the DOM)
  • Filters heroes based on the search input's value

For each change:

  • Hides an element leaving the DOM by setting its opacity and width to 0

  • Animates an element entering the DOM over 300 milliseconds. During the animation, the element assumes its default width and opacity.

  • If there are multiple elements entering or leaving the DOM, staggers each animation starting at the top of the page, with a 50-millisecond delay between each element

Animating the items of a reordering list link

Although Angular animates correctly *ngFor list items out of the box, it will not be able to do so if their ordering changes. This is because it will lose track of which element is which, resulting in broken animations. The only way to help Angular keep track of such elements is by assigning a TrackByFunction to the NgForOf directive. This makes sure that Angular always knows which element is which, thus allowing it to apply the correct animations to the correct elements all the time.

IMPORTANT :
If you need to animate the items of an *ngFor list and there is a possibility that the order of such items will change during runtime, always use a TrackByFunction .

Animations and Component View Encapsulation link

Angular animations are based on the components DOM structure and do not directly take View Encapsulation into account, this means that components using ViewEncapsulation.Emulated behave exactly as if they were using ViewEncapsulation.None ( ViewEncapsulation.ShadowDom behaves differently as we'll discuss shortly).

For example if the query() function (which you'll see more of in the rest of the Animations guide) were to be applied at the top of a tree of components using the emulated view encapsulation, such query would be able to identify (and thus animate) DOM elements on any depth of the tree.

On the other hand the ViewEncapsulation.ShadowDom changes the component's DOM structure by "hiding" DOM elements inside ShadowRoot elements. Such DOM manipulations do prevent some of the animations implementation to work properly since it relies on simple DOM structures and doesn't take ShadowRoot elements into account. Therefore it is advised to avoid applying animations to views incorporating components using the ShadowDom view encapsulation.

Animation sequence summary link

Angular functions for animating multiple elements start with query() to find inner elements; for example, gathering all images within a <div> . The remaining functions, stagger() , group() , and sequence() , apply cascades or let you control how multiple animation steps are applied.

More on Angular animations link

You might also be interested in the following:

  • Introduction to Angular animations
  • Transition and triggers
  • Reusable animations
  • Route transition animations
Last reviewed on Mon Feb 28 2022
Read article