Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
N

ngx-template-streams

> 前端框架
Open source

Small and lightweight Angular library that embraces reactivity and supercharges templates with Observables

200 stars0 likes2 views
WebsiteGitHub

About

Small and lightweight Angular library that embraces reactivity and supercharges templates with Observables

ngx-template-streams

Take your Angular templates to the next level by embracing reactivity. This is a small and lightweight library that provides a simple DSL enabling event streams in templates. In other words, this library will supercharge your templates with Observables. Use a declerative syntax to create Observables from different event sources, such as native DOM events, or component outputs.

⚠️ Disclaimer ⚠️

This library is experimental and its goal is to explore how to create event streams from templates in Angular. To do this, we hook into the build process and apply HTML and TypeScript transformations, as well as patch some other internal APIs to make this work with AOT.

We like reactive programming and with this experiment we hope to push this forward within the Angular community and to help drive the adoption of a similar syntax or feature set that is integrated into Angular.

Can I use this now? Definitely! If at some point our implementation breaks, or Angular releases its own syntax, we will provide a schematic that will help you seamlessly migrate your code to keep the impact on your projects as small as possible.

Features

  • ✅ Works with both ViewEngine and Ivy *
  • ✅ AOT compatible
  • ✅ Easy to use syntax that is inspired by this proposal
  • ✅ Ships with two reactive alternatives to ViewChild and ViewChildren (see API)
  • ✅ Can be used for native DOM events and component outputs
  • ✅ Redefine the event payload ($event)
  • ✅ Works with our beloved AsyncPipe

Notes

[1] If you want to use ngx-template-streams with Ivy you have to use the latest version of ngx-template-streams and upgrade your Angular version to >= 9.0.0-rc.0.

Credits

Big thanks to Filipe Silva, Craig Spence, Alexey Zuev and Manfred Steyer for his amazing ngx-build-plus library!

Table of contents

  • Quickstart
  • Syntax
  • Usage
  • API
  • Manual Installation
  • Why
  • Want to contribute?
  • Notes
  • FAQ
  • Versioning
  • Licence

Quickstart

The most straightforward way to get started with this library is to use its ng add schematic.

Simply run:

bash
ng add @typebytes/ngx-template-streams

This will do all the heavy (actually not so heavy) lifting for your and add the library to your project.

Optionally you can also specifiy a project with --project .

The schematic will:

  • ensure project dependency is placed in package.json
  • add ngx-build-plus as a devDependency
  • install necessary dependencies
  • configure serve, build, and test architects of your app (these will use a custom builder to allow for custom webpack configurations)

Once all that is done, we can take advantage of this library and define some event streams in our templates .

Alternative

If you want to use a more component- and code-centric way of listening for events on HTML elements or components, check out the @ObservableChild and @ObservableChildren decorator.

Syntax

The syntax is simple. Here's the full specification:

(*)="[; $event = ]"
  • * marks the event binding as a template stream binding
  • [] denotes optional parts of the synax
  • `` represent placeholders you can fill in

More specifically there are 3 core building blocks:

  1. event name
  2. template stream name
  3. payload

The payload is optional and can litereally be anything as long as it follows the syntax above. So optional doesn't mean you can go wild and define the payload in whatever form you like. More on this here.

Now, let's check out how we can use this in our app

Usage

Once you have installed the library, you can start using it. And that's very easy!

In order to create a template stream, you can use a slightly modified version of a regular event binding in Angular. Here's an example of a simple button with a click event:

xml
Click Me (Stream)

Instead of using a regular event binding, we are using a custom syntax that will be transformed into markup that Angular understands.

Important is that we indicate template streams by prefixing the event with an asterisk (*). For the expression of the template stream we use the name of the Observable that will emit the click event.

Note: The $ sign is only a convention and is used to denote the property as an Observable.

Next, we have to declare this property clicks$ on the component class. For that we can use a decorator provided by ngx-template-streams called @ObservableEvent():

typescript
import { Component, OnInit } from '@angular/core';
import { ObservableEvent } from '@typebytes/ngx-template-streams';
import { Observable } from 'rxjs';

@Component({...})
export class AppComponent implements OnInit {
  @ObservableEvent()
  clicks$: Observable;

  ngOnInit() {
    // we can either manually subscribe or use the async pipe
    this.clicks$.subscribe(console.log);
  }
}

Notice that we have declared the property using the @ObservableEvent decorator and subscribe to the Observable in our ngOnInit lifecycle hook. Alternatively we can also use this property in our template again and use the AsyncPipe.

That's it! That's all it takes to create a very simple template stream!

The general syntax for creating a simple template stream inside the template is:

(*)="; [payload]?"

The payload part is optional. For more information check out Overwriting the event payload.

Overwriting the event payload

By default, the event payload will be $event. Overwriting the payload is pretty straightforward and we only need to slightly extend our example from above.

So let's say we want the payload to be the string test. Then we can define the payload as follows:

xml
Click Me (Stream)

Here we slightly extend the expression with an assignment of $event. We can literally assign anything to $event, from primitive values, to objects, properties from the component, and even function calls.

The general syntax for overwriting the payload is:

$event = 

Adding operators

We have decided not to add too much magic to this library and focus a bit more on clarity over brevity, type safety and explicitness. This means that in order to add operators to the template stream, we have to declare another variable and use the template stream property (here clicks$) as the source.

For example:

typescript
import { Component, OnInit } from '@angular/core';
import { ObservableEvent } from '@typebytes/ngx-template-streams';
import { Observable } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

@Component({...})
export class AppComponent implements OnInit {
  @ObservableEvent()
  clicks$: Observable;

  // here we define a new property based on the template stream
  // in order to add operators
  debouncedClicks$ = this.clicks$.pipe(
    debounceTime(400)
  );

  ngOnInit() {
    this.debouncedClicks$.subscribe(console.log);
  }
}

API

Besides the template syntax, ngx-template-streams comes with one main building block, a @ObservableEvent() decorator.

@ObservableEvent(subjectOrSubjectFactory)

Parameters

Parameter Type Default Description
subjectOrSubjectFactory Subject or Subject Factory Subject Instance of a Subject or factory function to create the underlying source sequence for the template stream.

For example, if we don't pass any parameters it will create a plain Subject by default.

typescript
@Component({...})
export class AppComponent {
  @ObservableEvent()
  clicks$: Observable;
}

We can also pass in an instance of a Subject. This can be any type of Subject:

typescript
@Component({...})
export class AppComponent {
  @ObservableEvent(new BehaviorSubject('INIT'))
  clicks$: Observable;
}

Or, we could also pass in a factory function that creates a Subject:

typescript
@Component({...})
export class AppComponent {
  @ObservableEvent(() => {
    return new Subject();
  })
  clicks$: Observable;
}

@ObservableChild(selector, event, options)

The ObservableChild is a reactive alternative to ViewChild.

Parameters

Parameter Type Default Optional Description
selector name or component type /
event event name or output /
options QueryOptions & AddEventListenerOptions / x

QueryOptions (same options as with ViewChild)

{
  static?: boolean = false;
  read?: any;
}

AddEventListenerOptions

{
  once?: boolean;
  passive?: boolean;
}

Example:

typescript
import { Component } from '@angular/core';
import { ObservableChild } from '@typebytes/ngx-template-streams';

@Component({
  ...,
  template: `
    Click Me
  `
})
export class AppComponent {
  @ObservableChild('btn', 'click', { static: true, passive: true })
  clicks$: Observable;

  /**
   * We can only start to subscribe in 'ngOnInit' if the query is 'static'.
   * Otherwise we have to use 'ngAfterViewInit' or from the template
   * using the AsyncPipe.
   */
  ngOnInit() {
    this.clicks$.subscribe(console.log);
  }
}

@ObservableChildren(selector, event, options)

The ObservableChildren is a reactive alternative to ViewChildren.

Parameters

Parameter Type Default Optional Description
selector name or component type /
event event name or output /
options AddEventListenerOptions / x

Example:

typescript
import { Component } from '@angular/core';
import { ObservableChildren } from '@typebytes/ngx-template-streams';

@Component({
  ...,
  template: `
    
    
    
  `
})
export class AppComponent {
  @ObservableChildren(TestComponent, 'myOutput')
  aggregatedOutputs$: Observable;

  /**
   * We can only start to subscribe in 'ngAfterViewInit' or from the
   * template using the AsyncPipe.
   */
  ngAfterViewInit() {
    this.aggregatedOutputs$.subscribe(console.log);
  }
}

Manual Installation

If you want to manually install this libray you first have to install ngx-build-plus as a devDependency which allows us to extend the Angular CLI's default build behavior without ejecting:

bash
ng add ngx-build-plus

Note: If you don't want to use the install schematic and need to know how you can manually install ngx-build-plus, I would like redirect you to the official GitHub repo.

Next, we can install ngx-template-streams and save it as a dependency of our project:

bash
npm install @typebytes/ngx-template-streams -S

Now, we can update the angular.json and add some extra configuration options to the `bu

Issues· 7 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptangularrxjs

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category前端框架
PricingOpen source

> Related tools

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架