表中的Angular 4-添加行

时间:2018-09-26 13:30:22

标签: javascript angular service html-table

我有此服务订阅

callSearchService($event) {
   this.searchService.searchUser(this.firstName,this.lastName).subscribe(
    data => {
        console.log("we got: ", data);
        this.isNull(data.firstName,data.lastName);
    },
    error => {
        console.log("Error",error);
    },
);

我也有一张桌子。

 <thead>
      <tr>
        <th>#</th>
        <th>FirstName</th>
        <th>LastName</th>
      </tr>
    </thead>

当我从callSearchService获得用户信息(名字和姓氏)时,我很感兴趣如何向表中动态添加行

2 个答案:

答案 0 :(得分:0)

类似的东西

users = []; //user array

<thead>
      <tr>
        <th>#</th>
        <th>FirstName</th>
        <th>LastName</th>
      </tr>
    </thead>

<tbody>
<ng-container *ngFor="let user of users; let i=index;">
<tr>
<th>{{i}}</th>
<td>{{user.firstName}}</td>
<td>{{user.lastName}}</td>
</tr>
</ng-container>
</tbody>

当您收到新用户时,只需更新数组即可,其余的一切都可以正常工作

callSearchService($event) {
   this.searchService.searchUser(this.firstName,this.lastName).subscribe(
    data => {
        console.log("we got: ", data);
        this.isNull(data.firstName,data.lastName);
    this.users.push(data);
    },
    error => {
        console.log("Error",error);
    },
);

答案 1 :(得分:0)

You can use ngFor.

suppose you are getting the results in userdetails[] variable.


    <tr *ngFor="let userdetail of userdetails | async">
            <td>
              {{userdetail.firstName}}
            </td>
             <td>
              {{userdetail.lastName}}
            </td>
          </tr>