【发布时间】:2023-04-03 20:03:01
【问题描述】:
问题陈述
自定义管道应用于两个角度表达式{{fruits}} 和{{fruits | sortStringPipe:'asc' }} 但它应该只应用于我在表达式中传递pipe 符号的第二个。
代码库
mypipecomponent.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'cts-mypipecomponent',
templateUrl: './mypipecomponent.component.html',
styleUrls: ['./mypipecomponent.component.css']
})
export class MypipecomponentComponent implements OnInit {
fruits = ['mango','apple','banana','papaya','kiwi']
constructor() { }
ngOnInit() {
}
}
自定义管道(sort-string-pipe.pipe.ts)
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'sortStringPipe'
})
export class SortStringPipePipe implements PipeTransform {
transform(value: any, args?: any): any {
if(args === 'asc'){
return value.sort()
}
if(args === 'dsc'){
return value.sort().reverse()
}
return value.sort();
}
}
mypipecomponent.component.html
Unsorted Fruits: {{fruits}}
Sorted Fruits: {{fruits | sortStringPipe:'asc' }}
输出
Unsorted Fruits: apple,banana,kiwi,mango,papaya Sorted Fruits: apple,banana,kiwi,mango,papaya
在输出中,我们可以看到它对两个表达式都进行了排序,但它应该只对 {{fruits | sortStringPipe:'asc' }} 进行排序。
注意:如果我在两个表达式之间传递任何 HTML 元素,例如 <hr>,<br>,那么它可以工作,但我不想在表达式之间使用这些元素。
【问题讨论】:
-
嘿,这是一个非常有趣的错误!我建议您直接在 Angular 的 repo 上提出问题,因为它确实是一个错误。与此同时,您已经有了解决方法,在 SOF 上我们无能为力帮助您。
-
我用 stackblitz 添加了我的答案。试试这个,让我知道。