markdown Angular2 Snippets - 管道

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Angular2 Snippets - 管道相关的知识,希望对你有一定的参考价值。


## Pipes

* Used to transform output IN YOUR TEMPLATE

### Built-in pipes

* [https://angular.io/api?query=pipe](https://angular.io/api?query=pipe)
* Pass parameters separated by `:`, chain pipes with `|`:  
`{{ server.started | date: fullDate | uppercase }}`
* Order is important: parsed from left to right, one pipe is applied over the result of the previous pipe

### Custom pipes

Example: pipe for shorten a string: `ng generate pipe shorten`

shorten.pipe.ts  
```javascript
import { PipeTransform, Pipe } from '@angular/core';

@Pipe({ //we need the Pipe decorator, where you specify the name for the pipe
    name: 'shorten'
})
export class ShortenPipe implements PipeTransform {
    transform(value: any, limit: number) { //this class has to have an special method so that it can be used as a pipe. The transform() method receives the value to transform, and a list of optional arguments you can pass to the pipe
        return value.substr(0, limit) + ' ...'; //we always need to return    
	}
}
```

You need to import it in your app.module to use it, and add-it to declarations:

```javascript
import { ShortenPipe } from './shorten.pipe';

@NgModule({
  declarations: [
    AppComponent,
    ShortenPipe
  ],
```

And now you can use it in your template:  
`{{ server.name | shorten: 10 }}` 


### Async pipes

* Allows us to handle asynchronous data (observables, promises, etc)

Let's simulate an asynchronous piece of data:

```javascript
appStatus = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('stable');
    }, 2000);
  });
```

In our template:  
`{{ appStatus | async }}`  
You don't see anything at the beginning, and the value shows on the page when it's available.

以上是关于markdown Angular2 Snippets - 管道的主要内容,如果未能解决你的问题,请参考以下文章

markdown [快照] #snippet

markdown Snippet Utile

markdown [查看寻呼机不完整,添加片段示例] #android_snippet #android

Visual Studio Code配置Markdown文档的snippet不生效的解决

markdown Angular2 Snippets - 路由

markdown Angular2 Snippets - Observables