Table rows in a component in angular 2

I want to make a TableRowsComponent in angular 2 that displays several rows of a table.

I would like to use it in a template as follows:

<table class>
    <tbody>
        <table-rows *ngFor="#item of list" [someInput]="item"></table-rows>
    </tbody>
</table>

(So, "table-rows" will be the TableRowsComponent selector here). The TableRowsComponent template will look something like this:

<tr>
    <td> foo </td> 
    <td> bar </td>
</tr>
<tr *ngIf="something">
    ....
</tr>
<tr *ngFor="..">
     ...
</tr>

If we did this, the result is as follows:

<table class>
        <tbody>
            <table-rows>
                <tr>
                    ...
                </tr> 
                <tr>
                    ...
                </tr> 
            </table-rows>
            <table-rows>
                <tr>
                    ...
                </tr> 
                <tr>
                    ...
                </tr> 
            </table-rows> 
        </tbody>
</table>

Unfortunately, table-rows> elements ruined the rendering of the table. How to solve this problem? Maybe a way to make angular2 not display <table-rows> elements?

+4
source share
2 answers

you can use [table-rows], not table-rowswith the name of your selector.

eg.

`@Component({
    moduleId: module.id,
    selector: '[table-rows]',
    templateUrl: 'table-rows.component.html'
})`

tbody, ala <tbody table-rows></tbody>

+2
import { Component, Input, OnChanges } from '@angular/core';
import { FormGroup, FormBuilder, NgForm, REACTIVE_FORM_DIRECTIVES, Validators } from '@angular/forms';

    @Component({
      selector: '[dependent-row]',
      providers: [],
      template: `
        <tr [formGroup]="dependentForm">
          <td>
            <input type="text" formControlName="foo">
          </td>
          <td>
            <input type="text" formControlName="bar">
          </td>
        </tr>
      `,
      directives: [REACTIVE_FORM_DIRECTIVES]
    })
    export class DependentRowComponent implements OnChanges {
      @Input() dependent: any;
      _Form: any;

      constructor(fb: FormBuilder) {
        this.dependentForm = fb.group({
          foo: [''],
          bar: [''],
        })
      }

      ngOnChanges() {
        this._Form.find('foo').updateValue(this.dependent.foo);
        this._Form.find('bar').updateValue(this.dependent.bar);
      }
    }
0

Source: https://habr.com/ru/post/1649036/


All Articles