【问题标题】:Angular 2 *ngFor does not print to tableAngular 2 *ngFor 不打印到表格
【发布时间】:2017-11-29 00:39:00
【问题描述】:

我刚开始使用 Angular,但在显示从数据库中检索到的数据时遇到问题。有人能帮我理解为什么当我在这个 HTML 代码上使用 *ngFor 时,只有在我的 html 上显示,而不是其余的行吗?

这是我的 HTML 文件

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Lastname</th>
            <th>Email</th>
            <th>Phone</th>
            <th>School</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let contact contacts$">
            <td>{{ contact.first_name }}</td>
            <td>{{ contact.last_name }}</td>
            <td>{{ contact.email }}</td>
            <td>{{ contact.phone_number }}</td>
            <td>{{ contact.school }}</td>
        </tr>
    </tbody>
</table>

这是我的 component.ts 文件

import { Component, OnInit } from '@angular/core';
import { ContactService } from "./contacts.service";
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Contact } from './contact'

@Component({
  selector: 'app-contacts',
  templateUrl: './contacts.component.html',
  styleUrls: ['./contacts.component.css']
})

export class ContactsComponent implements OnInit {

  constructor( private router:Router, private contactService: ContactService )
  {}
    contacts$: Observable<Contact[]>;

    ngOnInit() {
        this.contacts$ = this.contactService.getContacts();
    }
}

我从 GET HTTP 调用中获取我的信息,如果我在标签上执行 *ngFor,它可以正常工作,但是当我在标签上使用它时它不会显示

这是我在

上执行此操作时的代码

<div *ngFor="let contact of contacts$ | async" >
  {{contact.first_name}}
</div>

【问题讨论】:

    标签: html angular2-template


    【解决方案1】:

    据我所知,您的 *ngFor tr 标签中缺少of。 您的 HTML 代码应如下所示

    <tbody>
            <tr *ngFor="let contact of contacts$"> <!-- adding of to retrive data -->
                <td>{{ contact.first_name }}</td>
                <td>{{ contact.last_name }}</td>
                <td>{{ contact.email }}</td>
                <td>{{ contact.phone_number }}</td>
                <td>{{ contact.school }}</td>
            </tr>
        </tbody>
    

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      您没有编写正确的循环语法,就像在这种情况下您缺少“of”一样,并且还交叉检查了正确的属性名称。

      <tbody>
        <tr *ngFor="let contact of contacts">
          <td>{{ contact.first_name }}</td>
          <td>{{ contact.last_name }}</td>
          <td>{{ contact.email }}</td>
          <td>{{ contact.phone_number }}</td>
          <td>{{ contact.school }}</td>
        </tr>
      </tbody>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-15
        • 2017-09-20
        • 2017-02-16
        • 1970-01-01
        • 2020-11-28
        • 1970-01-01
        相关资源
        最近更新 更多