我正忙着为Angular2编写我的第一个管道,我需要一些帮助把它放在一起 .
The problem: 我有一个api返回一组数字:1-2-03-4-5我想像这样设置这些数字:
<div class="number">1</div>
<div class="number">2</div>
<div class="number">03</div>
<div class="number">4</div>
<div class="number">5</div>
If this where PHP I wold simply go:
$array = explode("-","1-2-03-4-5");
foreach ($array AS $number) {
echo ' <div class="number">'.$number.'</div>';
}
My aim is to do this sort of thing in angular so I have created a pipe:
import {Pipe} from "angular2/core";
@Pipe({
name:"explode"
})
export class ExplodePipe {
transform(value) {
return some explody stuff here;
}
}
This is included in my component
import {Component, OnInit} from 'angular2/core';
import {RouteParams, ROUTER_DIRECTIVES} from "angular2/router";
import {HelpMenuComponent} from "./help-menu.component";
import {ExplodePipe} from "../Pipes/my.pipes";
@Component({
pipes:[ExplodePipe],
template: `
{{ExplodeMe | explode}}
`
...
export class ViewResultsComponent实现OnInit {ExplodeMe:“1-2-03-4-5”; }
-
我将在哪里插入要包含在输出中的HTML?这会是管道方法吗?我可以以某种方式告诉管道从{{}}部分以某种方式格式化吗?
-
管道可以使用哪些数据如何访问它?
谢谢!
2 回答
管道用于将数据作为输入,并将其转换为输出 . 转换功能的实现取决于您 . 但请记住,输出仍然需要是数据(它不能包含HTML) .
我建议你创建一个Pipe,它接受一个字符串并返回一个数组,使用短划线作为拆分分隔符:
在* ngFor表达式中使用管道循环遍历项目并格式化div中的每个项目:
Demo Plnkr
[Edit]
Building a Re-usable Component
如果您希望一直应用管道的公共模板,请将管道和模板组合成可重用的组件:
用法:
Demo Plnkr
所以我想我会发布我的最终解决方案 . 这基本上正是PHP爆炸所做的,并且非常有用!
My pipe:
And using the pipe in my html code:
Split some string: 1-2-3-4-5
Split some string: 12345
And in a real example:
Prints out:
这正是我想要的:)