【问题标题】:How to move body of a table into to another component, so it won't break styling如何将表格的主体移动到另一个组件中,这样它就不会破坏样式
【发布时间】:2019-06-19 09:14:45
【问题描述】:

我有一个非常大的表格组件,我想将它的主体部分分成新的组件。每次我尝试这样做时,表格的样式都会被破坏(因为我认为代码中有新的 HTML 结构)我使用的是 angular 5。

我尝试使用实际上位于原始表的正文部分中的代码创建一个新组件,但 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() {
  }
}

我重构后的表格:

<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 样式再次起作用?

【问题讨论】:

    标签: angular html-table components primeng ng-template


    【解决方案1】:

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

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

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

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

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

    在模板内部,您将无法再访问 &lt;td&gt; 标记,但组件具有 host 绑定,允许您更改组件的类或样式。

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

    【讨论】:

      猜你喜欢
      • 2019-08-18
      • 2011-08-19
      • 2017-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-22
      • 2021-04-08
      • 2019-08-26
      相关资源
      最近更新 更多