【问题标题】:How to access variable defined in *ngFor?如何访问 *ngFor 中定义的变量?
【发布时间】:2018-05-26 10:51:16
【问题描述】:

在我的第一个 Angular 4 应用程序中,我定义了一个列表组件:

<edm-document *ngFor="let document of documents" class="column is-one-quarter"></edm-document>

Document 是一个接口:

export interface Document {
    id?: Number,
    name: string,
    filePath: string
}

一切都按预期工作,即我得到了我的文档列表。但现在我想访问我的DocumentComponentedm-document 标签组件)中的文档变量

在我的 DocumentComponent 模板中,如果我尝试这样做,它就不起作用:

<p>{{ document.name }}</p>

我收到此错误:DocumentComponent.html:1 ERROR TypeError: Cannot read property 'name' of undefined.

我需要像这样强制执行文档定义,并将文档指定为输入:

<edm-document *ngFor="let document of documents" [document]="document" class="column is-one-quarter"></edm-document>

现在它可以工作了,但对我来说似乎有点多余,因为我在循环中定义了 let。这是否意味着使用let 定义的变量仅在设置了ngFor 指令的标签中可用?

我错过了什么吗?

谢谢,

尼古拉斯

【问题讨论】:

  • 是的,您只能访问 edm-document 标签及其所有子标签中的文档变量。

标签: javascript angular ngfor


【解决方案1】:

它可以工作,但对我来说似乎有点多余,因为我定义了一个 let in 循环

它并不像看起来那么多余,稍微重写一下就会变得很明显:

  • 如果没有明确定义组件应该使用什么(在您的示例中使用 [document]="document"),那么您的组件如何知道父变量名为 document?考虑:

    <edm-document *ngFor="let d of documents" [document]="d"></edm-document>
    

    有人可能会争辩说,Angular 可以引入一些parent 变量来访问外部循环变量,但是组件会知道它将如何使用,并且只能在循环中使用。可重用组件不应该意识到这一点。

  • 它怎么知道它可以直接使用那个循环变量,而不需要一些子属性呢?喜欢:

    <edm-document *ngFor="let d of documents" [document]="d.text"></edm-document>
    

所以:你的代码很好。

【讨论】:

    【解决方案2】:

    最初在 DOM 渲染期间,文档对象将 undefined

    • 使用类型安全的? 运算符

      <p>{{ document?.name }}</p>
      
    • 使用*ngIf,数组长度条件如下,

      <span *ngIf="documents.length > 0"> 
         <edm-document *ngFor="let document of documents" [document]="document" 
                       class="column is-one-quarter"></edm-document>
      </span>
      

    【讨论】:

      【解决方案3】:

      你也可以这样做

      <edm-document *ngFor="let document of documents" class="column is-one-quarter">
       <span class="something">{{document.name}}</span>
      </edm-document>
      

      并在 edm-document.component.html 中执行类似的操作

      <ng-content select=".something"></ng-content>
      

      【讨论】:

        【解决方案4】:

        循环的值(文档)在 *ngFor 放置的块内有效。在您的情况下:&lt;edm-document&gt;..&lt;/edm-document&gt;

        在你的例子中:

        <edm-document *ngFor="let document of documents"class="column is-one-quarter">
        <p>{{ document.name }}</p> <!-- document.name is valid -->
        </edm-document>
        <p>{{ document.name }}</p> <!-- document.name is invalid -->
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-04-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多