角组件,将两行添加到另一个表中

zrb*_*ker 5 angular

我正在创建一个组件“模板”(我认为这是正确的词),它可以是两行

@Componenet({
  selector: '[my-row]',
  template: `
  <tr>
    <td>first</td>
    <td>second</td>
  </tr>
  <tr *ngIf="secondRow">
    <td>foo</td>
    <td>bar</td>
  </tr>`
})
export class MyRowComponent {
  @Input() secondRow = false;
}
Run Code Online (Sandbox Code Playgroud)

我想在另一个这样的组件中使用

<table>
  <element my-row></element>
  <element my-row secondRow="true"></element>
  <element my-row></element>
  <element my-row></element>
</table>
Run Code Online (Sandbox Code Playgroud)

但是我不确定应该是什么“元素”。

如果我只想要一行,则可以从MyRowComponenet中删除“ tr”,然后将其制成<tr my-row></tr>,但是由于我想要两行,因此这似乎是不可能的。<tbody>这不是一个选择,因为我只能在一个表中有一个。

我尝试使用<ng-component><ng-template>但是使用它们时出现了模糊的错误。

对于我的用例,不需要使用div而不是表。

谁能帮我吗?

编辑:请注意,使elementbe tr不起作用。由于它只是在您要创建的表的第一个单元格内创建了一个表。这是证明这一点的两个组件。

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

@Component({
  selector: '[my-row]',
  template: `
  <tr>
    <td>{{ firstWord }}</td>
    <td>{{ secondWord }}</td>
  </tr>
  <tr *ngIf="secondRow">
    <td>fooooooooooooooo</td>
    <td>bar</td>
  </tr>
  `
})
export class MyRowComponent {
  @Input() firstWord = 'first';
  @Input() secondWord = 'second';
  @Input() secondRow = false;
}
Run Code Online (Sandbox Code Playgroud)

以及使用行的TableComponent。

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

@Component({
  selector: 'my-table',
  template: `
  <table class="table">
    <tr>
      <td>column 1</td>
      <td>column 2</td>
    </tr>
    <tr my-row firstWord="hello world" secondWord="good bye">
    <tr my-row secondRow="true">
    <tr my-row>
  </table>`
})
export class MyTableComponent {}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

yur*_*zui 3

我的建议是使用如下组件:

@Component({
  selector: 'tr[my-row]',
  template: `
    <td>{{ firstWord }}</td>
    <td>{{ secondWord }}</td>

    <ng-template #secondRow>
      <tr>
        <td>fooooooooooooooo</td>
        <td>bar</td>
      </tr>
    </ng-template>
  `
})
export class MyRowComponent {
  @Input() firstWord = 'first';
  @Input() secondWord = 'second';
  @Input() secondRow = false;

  @ViewChild('secondRow') template: TemplateRef<any>;

  constructor(private vcRef: ViewContainerRef) {}

  ngOnInit() {
    if(this.secondRow) {
      this.vcRef.createEmbeddedView(this.template);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

父级.html

<table class="table">
  <tr>
    <td>column 1</td>
    <td>column 2</td>
  </tr>
  <tr my-row firstWord="hello world" secondWord="good bye">
  <tr my-row secondRow="true">
  <tr my-row>
</table>
Run Code Online (Sandbox Code Playgroud)

笨蛋的例子