如何访问 *ngFor 中定义的变量?

How to access variable defined in *ngFor?

在我的第一个 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 指令的标记中可用?

我是不是漏掉了什么?

谢谢,

尼古拉斯

最初在 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>
    

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

在你的例子中:

<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 -->

你也可以这样做

<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>

it works but seems a bit redundant to me as I defined a let in loop

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

  • 如果没有明确定义组件应该使用什么(在您的示例中使用 [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>
    

所以:你的代码很好。