Search code examples
angularangular7

How to add component as child in angular


I have a problem with using component as child. I need to load some table value when user clicks on the button it should be rendered. But I have no clue for that. Here is the example:

@ViewChild(ConfigurationTableComponent) tableComponent: ConfigurationTableComponent;

And UI like:

<button class="btn btn-success" (click)="addElement()">Add new table row</button>

And the addElement() function:

  addElement(event: { stopPropagation: () => void; }) {
    this.table.nativeElement.insertAdjacentHTML('beforeend', ConfigurationTableComponent);
    event.stopPropagation();
  }

What I want is when I click the button it should add one more row into the table.

enter image description here

Here is an example


Solution

  • You're trying to do it jQuery way. Angular way it would be something like this:

          <tr *ngFor="let row of elements, let i = index">
            <td>{{i + 1}}</td>
            <td>{{row.lastName}}</td>
            <td>{{row.firstName}}</td>
            <td>{{row.age}}</td>
          </tr>
    
      elements = [];
    
      addElement() {
        this.elements = [...this.elements, {lastName: 'Doe', firstName: 'John', age: 26}]
      }
    

    Here's stackblitz: https://stackblitz.com/edit/angular-waxqv1?file=src/app/app.component.html