如何在ts而不是HTML中使用管道

Aru*_*agi 15 javascript pipe angular

我从ts添加文本到html元素

像这样

this.legend.append('text')
  .attr('x', legendRectSize + legendSpacing)
  .attr('y', legendRectSize - legendSpacing)
  .text(function(d) { return d; });
Run Code Online (Sandbox Code Playgroud)

这将创建html之类的

<text>Data will come here</text>
Run Code Online (Sandbox Code Playgroud)

我想使用管道将这些数据转换成某种形式我该如何从ts代码中做到这一点?

当我动态创建这个HTML时,我不能像这样使用管道

<text>{{Data will come here | pipename}} </text>
Run Code Online (Sandbox Code Playgroud)

我正在寻找喜欢的东西

this.legend.append('text')
  .attr('x', legendRectSize + legendSpacing)
  .attr('y', legendRectSize - legendSpacing)
  .text(function(d) { return d; }).applypipe('pipename');
Run Code Online (Sandbox Code Playgroud)

Bha*_*han 20

首先在组件中导入管道.然后在组件中使用管道.像这样..

pipe.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;
        }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

component.ts(在你的打字稿代码中使用)

const filterPipe = new FilterPipe();
const fiteredArr = filterPipe.transform(chkArray,txtSearch);
Run Code Online (Sandbox Code Playgroud)

xyz.html(在你的html文件中使用)

<ul>
    <li *ngFor="todo for todos | filter:'txtsearch'"> {{todo.name}} </li>
</ul>
Run Code Online (Sandbox Code Playgroud)


sud*_* KB 11

如果Pipename是您的自定义管道,那么如果您想在ts文件中使用相同的管道,那么您可以使用下面的代码

import {Pipename} from './pipename';

Pipename.prototype.transform(arguments);//this is how u can use your custom pipe
Run Code Online (Sandbox Code Playgroud)

  • 那正是我想要的 (2认同)

小智 9

在组件中导入管道

import { PipeName } from './pipename'
Run Code Online (Sandbox Code Playgroud)

包括在提供中

@Component({
    selector: 'pipe-using-component',
    templateUrl: './pipe-using-component.html',
    providers: [
        PipeName
    ],
})
Run Code Online (Sandbox Code Playgroud)

将其注入构造函数

export class PipeUsingComponent {
  constructor(private pipeName: PipeName)
   }

   var requiredResult = this.pipeName.transform(passvalue);
}
Run Code Online (Sandbox Code Playgroud)


Zoh*_*had 6

在你的.ts中

import {YourPipe} from '/pipePath';


let value = new YourPipe().transform(param);
Run Code Online (Sandbox Code Playgroud)