Javascript 如何在 ts 中使用管道而不是 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39653630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use pipe in ts not HTML
提问by Arun Tyagi
I adding text into html element from ts
我将文本从 ts 添加到 html 元素中
like this
像这样
this.legend.append('text')
.attr('x', legendRectSize + legendSpacing)
.attr('y', legendRectSize - legendSpacing)
.text(function(d) { return d; });
this will create html like
这将创建 html 之类的
<text>Data will come here</text>
I want to use pipe to convert this data into some form how can I do that from ts code ?
我想使用管道将这些数据转换为某种形式,我该如何从 ts 代码中做到这一点?
and as I am creating this HTML dynamically I cannot use pipe like this
当我动态创建这个 HTML 时,我不能像这样使用管道
<text>{{Data will come here | pipename}} </text>
I am looking for somethig like
我正在寻找类似的东西
this.legend.append('text')
.attr('x', legendRectSize + legendSpacing)
.attr('y', legendRectSize - legendSpacing)
.text(function(d) { return d; }).applypipe('pipename');
回答by Bharat Chauhan
First import your pipe in component. And then use your pipe in your component. Like this..
首先在组件中导入您的管道。然后在您的组件中使用您的管道。像这样..
pipe.ts
管道.ts
/**
* filter checkbox list
*/
@Pipe({ name: 'filter', pure: true })
export class FilterPipe{
transform(items: any[], args: any): any {
let filter = args.toString();
if(filter !== undefined && filter.length !== null){
if(filter.length === 0 || items.length ===0){
return items;
}else{
return filter ? items.filter(item=> item.title.toLocaleLowerCase().indexOf(filter) != -1) : items;
}
}
}
}
component.ts(Use in your typescript code)
component.ts(在您的打字稿代码中使用)
const filterPipe = new FilterPipe();
const fiteredArr = filterPipe.transform(chkArray,txtSearch);
xyz.html(Use in your html file)
xyz.html(在您的 html 文件中使用)
<ul>
<li *ngFor="todo for todos | filter:'txtsearch'"> {{todo.name}} </li>
</ul>
回答by R.C.VISHNU Vardhan
import pipe in the component
在组件中导入管道
import { PipeName } from './pipename'
include it in the provides
将其包含在提供中
@Component({
selector: 'pipe-using-component',
templateUrl: './pipe-using-component.html',
providers: [
PipeName
],
})
inject it in the constructor
将其注入构造函数
export class PipeUsingComponent {
constructor(private pipeName: PipeName)
}
var requiredResult = this.pipeName.transform(passvalue);
}
回答by Sudheer KB
If Pipename is your custom pipe then if you want to use the same in your ts file then you can use below code
如果 Pipename 是您的自定义管道,那么如果您想在 ts 文件中使用相同的管道,则可以使用以下代码
import {Pipename} from './pipename';
Pipename.prototype.transform(arguments);//this is how u can use your custom pipe
回答by Zoha Irshad
In your .ts
在你的 .ts
import {YourPipe} from '/pipePath';
let value = new YourPipe().transform(param);