你如何运行NgFor在Angular2结果的功能? [英] How do you run a function on the result of NgFor in Angular2?
问题描述
考虑系统中所有用户的列表:
Consider a list of all of the users in your system:
allUsers = {
a: {name:'Adam',email:'adam@testco.com',level:'admin',group:'Owners'},
b: {name:'Barbra',email:'Barbra@testco.com',level:'admin',group:'Owners'},
c: {name:'Chris',email:'Chris@otherplace.net',level:'standard',group:'Managers'},
d: {name:'Dennis',email:'dsmolek@showman.com',level:'standard',group:'Managers'},
e: {name:'Elizabeth',email:'eadams@testco.com',level:'standard',group:'Staff'},
f: {name:'fred',email:'fred@testco.com',level:'visitor',group:'Visitor'},
}
然后,用户在一个项目的列表:
Then a list of the users on a project:
usersList = ['a','b','d','f'];
所以,你有一个很好的功能,方便取的用户ID和查找的用户详细信息的其余部分:
So you have a nice easy function to take the user id and lookup the rest of the user details:
getUser(userId){
console.log('Getting User with Id:', userId);
if(allUsers[userId]) return allUsers[userId];
}
然后在模板中使用* ngFor遍历在列表中的用户,但你要那么查找的全套细节
Then in the template you use *ngFor to loop through the users in the list, but you want to then lookup the full set of details
<tr *ngFor="#userId in usersList" #user="getUser(userId)">
<td>{{user.name}}</td>
</tr>
没有工作...
如果没有创建自定义组件或其它更复杂的东西,我无法弄清楚如何每个用户运行一次的getUser功能。我当然可以一遍又一遍地像运行:
Doesn't work... Without creating custom components or other more complex stuff I can't figure out how to run the getUser function once per user. I can of course run it over and over like:
<td>{{getUser(userId).name}}</td>
但这似乎并不像最好的办法。
是否有更简单的方式来获得访问用户id变量,并将其设置为一个局部变量?
but this doesn't seem like the best way. Is there an easier way to get access to the userId variable and set it as a local variable?
这里是我一直在玩什么迄今一个plunker
Here's a plunker of what I've been playing with so far
推荐答案
虽然你可以创建ngFor模板指令的变量,但该变量只能取指数,偶,奇和放值;持续。
Though you can create a variable on ngFor template directive, but that variable can only take value of index, even, odd & last.
这就是为什么我会用管这种情况下,你需要通过 usersList
&安培; ALLUSERS
自定义 @Pipe
getUsers(它将起到相同Angular1过滤器)。
Thats why I could use pipe for this case, where you need to pass usersList
& allUsers
to custom @Pipe
getUsers (it will act same as a filter in Angular1).
标记
<tr *ngFor="#user of usersList | getUsers: allUsers">
<td>
{{user.name}}
</td>
<td>
{{user.email}}
</td>
<td>
{{user.level}}
</td>
<td>
{{user.group}}
</td>
</tr>
code
@Pipe({
name: 'getUsers',
pure: false
})
export class GetUserPipe implements PipeTransform {
constructor(){
this.test = 'Test';
}
transform(array:Array<string>, object: any) : any {
// for..in loop
let output = [];
for (var num in array)
{
// somehow object goes inner side
output.push(object[0][array[num]]);
}
console.log(output)
return output;
}
}
这篇关于你如何运行NgFor在Angular2结果的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!