如何将 table 的主体移动到另一个组件中,这样它就不会破坏样式

How to move body of a table into to another component, so it won't break styling

我有一个相当大的 table 组件,我想将其正文部分分离到新组件中。每次我尝试这样做时,table 的样式都会被破坏(因为我认为代码中有新的 HTML 结构)我正在使用 angular 5.

我曾尝试使用实际上位于原始 table 正文部分内的代码创建一个新组件,但 UI 以可怕的方式呈现,看起来不很好。列坏了,checkbnoxes 也坏了。我认为 ngPrime 样式不起作用,我很确定。

原代码:

<p-table 
         [value]="data"
         ...
>
  <ng-template  pTemplate="body" let-row let-expanded="expanded" let-rowIndex="rowIndex">
    <tr class="cursor-pointer" 
        [pContextMenuRow]="row"
        [pSelectableRow]="row"
        [pSelectableRowIndex]="rowIndex">

      <td *ngFor="let col of columns" class="{{col.styleClass}}">
        <span class="ui-column-title">{{col.header}}</span>
        <p-checkbox
          *ngIf="shouldShowCheckbox()"
          binary="true"
          [disabled]="!isEditable"
          (onChange)="toggle($event, col.field, rowIndex)">
        </p-checkbox>
      </td>
    </tr>
  </ng-template>


</p-table>

我的代码在 html 文件中:

<tr class="cursor-pointer"
    [pContextMenuRow]="row"
    [pSelectableRow]="row"
    [pSelectableRowIndex]="rowIndex">

  <td *ngFor="let col of columns" class="{{col.styleClass}}">
    <span class="ui-column-title">{{col.header}}</span>
    <p-checkbox
      *ngIf="shouldShowCheckbox()"
      binary="true"
      [disabled]="!isEditable"
      (onChange)="toggle($event, col.field, rowIndex)">
    </p-checkbox>
  </td>
</tr>

我在 TS 文件中的代码:

@Component({
  selector: 'table-body',
  template: './table-body.component.html',
  styleUrls: ['./table-body.component.scss']
})
export class TableBodyComponent implements OnInit {

  @Input() columns: any[];
  @Input() row: any;
  @Input() rowIndex: number;
  @Input() isEditable: boolean;

  constructor() {
  }

  ngOnInit() {
  }
}

Table 重构后:

<p-table 
         [value]="data"
         ...
>
  <ng-template  pTemplate="body" let-row let-expanded="expanded" let-rowIndex="rowIndex">
    <table-body [columns]="columns"
                [row]="row"
                [rowIndex]="rowIndex"
                [isEditable]="isEditable"
    ></table-body>
  </ng-template>


</p-table>

因此,我希望在重构后拥有完全相同的页面。有谁知道如何将样式传递给这个新的子组件,或者如何使这个 ng 样式再次起作用?

您需要对组件使用属性选择器。

所以你会像这样使用组件:

<p-table [value]="data">
  <ng-template  ...>
    <tr table-body ...></tr>
  </ng-template>
</p-table>

然后您可以像这样定义选择器:

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

在模板中,您将无法再访问 <td> 标记,但该组件具有 host 绑定,可让您更改 类 或样式组件。

https://angular.io/api/core/Directive#host