一款小巧轻量的 Angular 库,它拥有反应性,并通过 Observable 为模板提供强大的支持
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.
ViewEngine and Ivy *ViewChild and ViewChildren (see API)$event)AsyncPipeNotes
[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.
Big thanks to Filipe Silva, Craig Spence, Alexey Zuev and Manfred Steyer for his amazing ngx-build-plus library!
The most straightforward way to get started with this library is to use its ng add schematic.
Simply run:
ng add @typebytes/ngx-template-streamsThis 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:
package.jsondevDependencyserve, 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 .
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.
The syntax is simple. Here's the full specification:
(*)="[; $event = ]"* marks the event binding as a template stream binding[] denotes optional parts of the synaxMore specifically there are 3 core building blocks:
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
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:
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():
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.
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:
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 = 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:
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);
}
}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.
@Component({...})
export class AppComponent {
@ObservableEvent()
clicks$: Observable;
}We can also pass in an instance of a Subject. This can be any type of Subject:
@Component({...})
export class AppComponent {
@ObservableEvent(new BehaviorSubject('INIT'))
clicks$: Observable;
}Or, we could also pass in a factory function that creates a Subject:
@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:
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:
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);
}
}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:
ng add ngx-build-plusNote: 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:
npm install @typebytes/ngx-template-streams -SNow, we can update the angular.json and add some extra configuration options to the `bu
暂无开放 Issues,或尚未同步最近议题。