简体   繁体   English

Angular:是否可以在循环模板中创建变量?

[英]Angular: Is it possible to create a variable inside template for loop?

I have a *ngFor inside my template where I want to call a function on each item. 我的模板中有一个* ngFor,我想在每个项目上调用一个函数。 the function returns an object with three values that I want to display inside my template. 该函数返回一个对象,该对象具有要在模板中显示的三个值。 The problem right now is that I am calling the function three times to display all properties of the object. 现在的问题是我要调用该函数三次以显示对象的所有属性。

What I want to do is bind the result to a variable so that I can then use the variable instead of calling the function 3 times. 我想做的就是将结果绑定到变量,这样我就可以使用变量而不是调用函数3次。 So what I want to achieve is something like the following: 所以我想要实现的是以下内容:

var lists = [['a', 'b', 'c'], ['k', 'd', 't']];

function addx(letters){
    return {
    'item1': letters[0] + 'x',
    'item2': letters[1] + 'x',
    'item3': letters[2] + 'x',
  }
}

for(var i=0; i<lists.length; i++){
    var a = addx(lists[i])
  console.log(a.item1);
  console.log(a.item2);
  console.log(a.item3);
}

Maybe I haven't understood exactly what you want, but wouldn't a simple 'map' do? 也许我不确定您想要的是什么,但是简单的“地图”不会做到吗? specifically 特别

let newList = lists.map(addx);

The you can use newList for your ngFor 您可以将newList用于ngFor

 var lists = [['a', 'b', 'c'], ['k', 'd', 't']]; function addx(letters){ return { 'item1': letters[0] + 'x', 'item2': letters[1] + 'x', 'item3': letters[2] + 'x', } } var newList = lists.map(addx); console.log(newList); 

You can use something called "Pipe" in the ngFor syntax. 您可以在ngFor语法中使用称为“管道”的名称。

The following documentation uses it to filter the ngFor list, but it could be used to map the elements using the function you defined. 以下文档使用它来过滤ngFor列表,但也可以使用您定义的函数来映射元素。

Your template would be something like: 您的模板如下所示:

<div *ngFor="let obj of (objs | myPipe)">

And your pipe: 而你的管道:

import { Pipe, PipeTransform } from '@angular/core';
import { MyType } 

@Pipe({ name: 'myPipe' })
export class MyPipe implements PipeTransform {
  transform(objs: MyType[]) {
    return objs.map(addx); // Your function
  }
}

Now, inside your template, you should use the object returned by your mapping function. 现在,在模板内部,应该使用映射函数返回的对象。

Source: https://angular.io/guide/pipes#flyingheroespipe 资料来源: https : //angular.io/guide/pipes#flyingheroespipe

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM