简体   繁体   English

如何遍历模板中的数组?

[英]How do I loop through an array in a template?

I am using Angular's schematics in a project. 我在项目中使用Angular的原理图

I have an array of numbers: const numbers = [1, 2, 3, 4, 5] 我有一个数字数组: const numbers = [1, 2, 3, 4, 5]

And I want to print them out in an HTML template. 我想将它们打印在HTML模板中。 I am passing the array in the following way: 我通过以下方式传递数组:

export function schematics(_options: Schema): Rule {
  return (tree: Tree, _context: SchematicContext) => {
    const numbers = [1, 2, 3, 4, 5];

    const sourceTemplate = url('./files');
    const sourceParametrizedTemplate = apply(sourceTemplate, [
      template({
        ..._options,
        ...strings,
        numbers
      })
    ]);

    return mergeWith(sourceParametrizedTemplate)(tree, _context);
  };
}

I was thinking about doing something like this: 我正在考虑做这样的事情:

index.html 的index.html

<h1>Numbers</h1>

  <%= for(let n in numbers) { =>

  <p><%= n %></p>

  <%= } %>

But I get the error SyntaxError: Unexpected token for . 但是我收到了错误SyntaxError: Unexpected token for

Does anyone know what is the correct way of achieving it? 有谁知道实现它的正确方法是什么? I was not able to find it in the documentation. 我在文档中找不到它。

Thank you! 谢谢!

I finally found it! 我终于找到了! I had to use <% instead of <%= in the blocks with logic. 我必须在逻辑块中使用<%而不是<%=

<%= should only be used for blocks that you want to display. <%=仅应用于要显示的块。

Final version: 最终版本:

<h1>Numbers</h1>

  <% for(let n in numbers) { =>

  <p><%= n %></p>

  <% } %>

By the way, the result I was looking for I got it using for ... of ... instead of for ... in ... , but they both work. 顺便说一句,我一直在寻找的结果是使用for ... of ...而不是for ... in ... ,但是它们都可以工作。

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

相关问题 如何在angular / Ionic中循环嵌套数组 - How do I loop through a nested array in angular/Ionic 如何遍历html中的Set - How do I loop through a Set in the html 如何循环遍历对象数组中的对象数组并使用 Angular/Ionic 在我的 HTML 中显示? - How do I loop through an array of objects that's within an array of objects and display in my HTML using Angular/Ionic? 如何循环通过 Angular HTTP 响应? - How do I loop through an Angular HTTP Response? 如何使用 ngFor 仅遍历元素的子集? - How do I loop through only a subset of elements using ngFor? 我如何循环通过 angular 11 中的 http 请求的响应 - how do i loop through the response of an http request in angular 11 如何遍历数组数组? - How to loop through an array of arrays? 每次将新对象推入数组时,我的循环都会在模板中重复出现。 我怎么能在模板中处理这个? - every time a new object is pushed into array my loop in template repeats. how can I handle this in template? 如何使用 *ngFor 在模板中反向显示数组? - How do I show an array in reverse in a template using *ngFor? 如何在模板中没有函数的情况下使用 *ngFor 循环格式化模板中的数据? - How do I format data in a template using a *ngFor loop without having functions in the template?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM