Angular 2 * ngFor不打印到表格

时间:2017-11-29 00:39:00

标签: html angular2-template

我是使用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>

1 个答案:

答案 0 :(得分:0)

据我所知,你错过了* 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>

希望它有所帮助。