javascript - ngFor 不适用于 <tr> 元素

标签 javascript angular

所以我正在我的 MEAN-stack 应用程序中开发一个论坛,并且我从我的 node.js 后端请求了这些部分。我能够从后端接收我想要的内容,但是当我想显示检索到的 4 个部分时,我无法使行显示在屏幕上。我在我的子论坛上做了同样的机制,它似乎在那里工作,但我不明白是什么让它不起作用。

我的论坛模板 (forum.component.html)

<div class="row justify-content-center mb-3 mt-5">
    <div class="col-md-8">
        <table class="table">
            <thead>
            <tr>
                <th>Forum</th>
                <th>Posts</th>
                <th>Replies</th>
                <th>Last Post</th>
            </tr>
            </thead>
            <tbody>
            <tr *ngFor="let section of sections" [routerLink]="section.name">
                <td>
                    <p><b>{{section.name}}</b></p>
                    <p>For all general topics of Wizards Unite.<br> Ask a question or open a topic te contribute to the community.</p>
                </td>
                <td>{{section.posts.length}}</td>
                <td>{{section.totalReplies}}</td>
                <td>
                    <p>{{section.lastPost.title}}</p>
                    <p>by {{section.lastPost.name}} on {{section.lastPost.date | amDateFormat:'LL'}}</p>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
    <div class="col-md-2 side-column">

    </div>
</div>

我的论坛组件 (forum.component.ts)

import {Component, OnInit} from "@angular/core";
import {ForumService} from "./forum.service";
import {ActivatedRoute} from "@angular/router";

@Component({
    selector: 'forum',
    templateUrl: 'forum.component.html',
    styleUrls: [
        'forum.component.css'
    ]
})

export class ForumComponent implements OnInit {

    sections = [];

    constructor(private forumService: ForumService, private route: ActivatedRoute){}

    ngOnInit(){

            this.forumService.getSections()
                .subscribe(function (sections:any) {
                    this.sections = sections.obj;
                    console.log(this.sections);
                })

    }
}

这是我从组件中的 getSections() 函数收到的数据。乍一看,一切都如我所愿,但正如您所看到的,行没有出现在屏幕的左侧*

enter image description here

最佳答案

当调用回调函数时,this 的上下文通常会发生变化。

在您的示例中,this 不再引用该类,因此它没有按照您的预期设置sections

函数(sections:any)更改为(sections:any)=>。通过使用箭头函数,它应该保留其上下文

关于javascript - ngFor 不适用于 <tr> 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50399322/

相关文章:

angular - 如何使用jspdf和html2canvas全屏打印

javascript - Vue 过渡的动态样式

javascript - 当子输入发生更改时,如何使用 jQuery 获取最接近的表单数据?

javascript - 异步/等待隐式返回 promise ?

angular - APP_INITIALIZER阻止在错误时加载应用

javascript - 如何修复在 Angular 4 中找不到模块 'typescript'?

javascript - 使用javascript将数据传回父级

javascript - 在 Leaflet.js 中,有没有办法迭代所有当前存在的标记?

Angular Material 和 CDK 更新 7 到 8 迁移失败

angular 2 router.events 订阅未触发