如何在Angular 7中的表中添加行组件?

时间:2019-04-01 00:33:53

标签: javascript angular components

我使用的是angluar的最新版本。 (7.2.0) 我有个人tr组件,例如:

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

@Component({
selector: 'app-table-row',
templateUrl: './table-row.component.html',
styleUrls: ['./table-row.component.scss']
})
export class TableRowComponent implements OnInit {
@Input() character: any;
@Input() columns: string[];

constructor() { }

ngOnInit() {
}

}

我想在表格中使用此组件,例如:

<table class="mat-elevation-z8">
<tr>
   <th *ngFor="let c of columns">{{c}}</th>
</tr>
<tr app-table-row class="component-style table-row-component" *ngFor="let ch of characters | async" 
   [character]="ch" 
  [columns]="columns">
</tr>

</table>

得到类似这样的错误

Can't bind to 'character' since it isn't a known property of 'tr'. ("table-row class="component-style table-row-component" *ngFor="let ch of characters | async" 
       [ERROR ->][character]="ch" 
      [columns]="columns">
  </tr>
"): ng:///AppModule/TableComponent.html@7:7

如何在表格内正确添加我的组件?

2 个答案:

答案 0 :(得分:1)

将组件选择器定义为带有方括号的属性选择器:

@Component({
  selector: 'tr[app-table-row]',
  ...
})

以便可以将其设置为tr元素的属性:

<tr app-table-row ...>

答案 1 :(得分:0)

正如@ConnorsFan 提到的,您需要通过在组件的选择器中添加方括号来将您的组件定义为属性,但无需在其前面添加“tr”,因此以下内容应该没问题:

@Component({
  selector: '[app-table-row]',
  ...
})

然后使用如下:

<tr app-table-row 
    *ngFor="let item of items"
    [myProp]="item"
    (myEvent)="executeEvent($event)"
    ...>
</tr>