Yuv*_*als 19 angular-pipe angular
我试图limitTo在字符串上运行Angular2上的管道:
{{ item.description | limitTo : 20 }}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
The pipe 'limitTo' could not be found
Run Code Online (Sandbox Code Playgroud)
这是我的 app.module
从'./limit-to.pipe'导入{TruncatePipe};
@NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
InMemoryWebApiModule.forRoot(InMemoryDataService),
RouterModule.forRoot([
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
},
{
path: 'home',
component: GridComponent
},
])
],
declarations: [
AppComponent,
TopNavComponent,
GridComponent,
TruncatePipe
],
providers: [
PinService,
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
我使用管道的网格组件:
import { Component,OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
moduleId : module.id,
selector: 'my-grid',
templateUrl : 'grid.component.html',
styleUrls: [ 'grid.component.css']
})
export class GridComponent implements OnInit{
constructor(
private router: Router,
private gridService: GridService) {
}
ngOnInit(): void {
}
}
Run Code Online (Sandbox Code Playgroud)
我的管道定义:
import { PipeTransform, Pipe } from '@angular/core';
@Pipe({
name: 'limitToPipe'
})
export class TruncatePipe implements PipeTransform {
transform(value: string, limit: number) : string {
let trail = '...';
return value.length > limit ? value.substring(0, limit) + trail : value;
}
}
Run Code Online (Sandbox Code Playgroud)
最后我的模板:
<div *ngFor="let item of items" class="grid-item">
<p class="simple-item-description">
{{ item.description | limitToPipe : 20 }}
</p>
</div>
Run Code Online (Sandbox Code Playgroud)
小智 66
为了回答你的问题,如果它被删除:是和否.limitTo似乎被删除了,但有一个slice管道基本上做同样的limitTo,可以用于字符串以及列表.它也让你有机会在一个给定的起始指数开始你的限制,这是很整洁.
在你的情况下,一个简单{{ item.description | slice:0:20 }}就足够了.除非你想获得更多写自己管道的经验,我甚至鼓励;)
来源和文档:https://angular.io/docs/ts/latest/api/common/index/SlicePipe-pipe.html
Lib*_*hew 21
首先,您需要创建一个管道.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'limitTo'
})
export class TruncatePipe {
transform(value: string, args: string) : string {
// let limit = args.length > 0 ? parseInt(args[0], 10) : 10;
// let trail = args.length > 1 ? args[1] : '...';
let limit = args ? parseInt(args, 10) : 10;
let trail = '...';
return value.length > limit ? value.substring(0, limit) + trail : value;
}
}
Run Code Online (Sandbox Code Playgroud)
在module.ts文件中添加管道
import { NgModule } from '@angular/core';
import { TruncatePipe } from './app.pipe';
@NgModule({
imports: [
],
declarations: [
TruncatePipe
],
exports: [
]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
然后在绑定代码中使用管道:
{{ item.description | limitTo : 20 }}
Run Code Online (Sandbox Code Playgroud)
演示人员
我添加了此代码以使其更有意义
{{ item.description | slice:0:20 }}{{ item.description.length > 20 ? '....read more' : '' }}
Run Code Online (Sandbox Code Playgroud)
显示数据被切片并包含更多隐藏的数据
| 归档时间: |
|
| 查看次数: |
25477 次 |
| 最近记录: |