对表行项使用指令而不重复

问题描述 投票:0回答:2

用户-component.html

<table class="table table-hover">
    <thead class="text table-head-font">
        <tr>
            <th>ID</th>
            <th>First Name</th>
            <th>Last Name</th>         
        </tr>
    </thead>
    <tbody>
        <tr (dblclick)="selectUser()">
            <td>{{id}}</td>
            <td>{{firstName}}</td>
            <td>{{lastName}}</td>            
        </tr>
    </tbody>
</table>

app.component.html

这将为表中的每个记录呈现thead,我想避免它。

我尝试重构这个以将table tr项放在users-component.html和table header中,以便在app.component.html app.component中留在外面。

<table class="table table-hover">
    <thead class="text table-head-font">
        <tr>
            <th>ID</th>
            <th>First Name</th>
            <th>Last Name</th>         
        </tr>
    </thead>
    <tbody>
        <users *ngFor="let user of users" (openUser)="getUser($event)" [id]="user.Id" [firstName]="this.firstName" [lastName]="this.lastName"></users>
    </tbody>
</table>

用户-component.html

<tr (dblclick)="selectUser()">
    <td>{{id}}</td>
    <td>{{firstName}}</td>
    <td>{{lastName}}</td>            
</tr>

但这会使所有东西都在第一个td下,其余的td和tr都是空的。

更新

用户-component.ts

@Component({
    selector: 'users',
    templateUrl: './users-component.html'
})
html angular
2个回答
0
投票

users-component.ts添加一个tr选择器:

@Component({
    selector: 'tr',
    ...
})

然后在app.component.html使用users-component像这样:

<tr users></tr>


0
投票

以下是一种可以帮助您实现这一目标的方法。您可以将用户列表作为Input传递给用户组件,然后自己显示用户。名称可能根据您的选择而有所不同。

以下是供参考的代码。

这是以下代码app.component.ts的现场Demo

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 5';
  userList = [
    {
      id:"1",
      name:"user1",
      email:"[email protected]"
    },
     {
      id:"2",
      name:"user2",
      email:"[email protected]"
    },
     {
      id:"3",
      name:"user3",
      email:"[email protected]"
    }
  ]
}

app.component.html

<users [users]="userList"></users>

user.component.html

<table class="table table-hover">
    <thead class="text table-head-font">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>         
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let user of users" (dblclick)="selectUser()">
            <td>{{user.id}}</td>
            <td>{{user.name}}</td>
            <td>{{user.email}}</td>            
        </tr>
    </tbody>
</table>

user.component.ts

import { Component, Input } from '@angular/core';

@Component({
  selector: 'users',
  templateUrl: './user.component.html',
  styleUrls: [  ]
})
export class UserComponent  {
  @Input() users: any;
}

希望这可以帮助 :)

© www.soinside.com 2019 - 2024. All rights reserved.