3
votes

I'm the begginer with angular4, and i am trying to build bootstrap table with nested components, the child component is display in single row. But table is not display correctly.please see the below image

snapshot

parent component

<table class="table table-dark">
  <thead>
    <tr>
      <th>Title</th>
      <th>Done</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
    <app-child *ngFor="let todo of this.todos " [todo]="todo" (eventRemove)="remove(todo)"></app-child>
  </tbody>
</table>
<hr>
<div>
  <form #f="ngForm" (ngSubmit)="formSubmit(f.value)">
    <label for="title"></label>
    <input type="text" name="title" id="title" [(ngModel)]="this.todo.title">
    <button type="submit">Add</button>
  </form>
</div>



import { Todo } from '../todo';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  public todos: Todo[] = [];
  public todo: Todo = { title: "", done: false };
  formSubmit(value) {
    var todo = { title: value.title, done: false };
    this.todos.push(todo);
  }
  constructor() {


  }

  ngOnInit() {
    this.todos.push({ title: "clean your room", done: false });
    this.todos.push({ title: "clean your desk", done: true });

  }
  remove(t) {
    let index = this.todos.indexOf(t);
    this.todos.splice(index, 1);
    console.log("removed", t);
  }

}

Child component

<tr>
    <td>
        {{todo.title}}
    </td>
    <td>
        <input type="checkbox" [checked]="todo.done">
    </td>
    <td>
        <button class="btn btn-success btn-sm" (click)="onRemove(todo)">Remove</button>
    </td>
</tr>

import { Todo } from '../todo'; import { Component, Input,Output, OnInit ,EventEmitter} from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})

    export class ChildComponent implements OnInit {

      @Input()
      todo: Todo;
      @Output()
      eventRemove = new EventEmitter<Todo>();
      constructor() { }

      ngOnInit() {
      }
      onRemove(data) {

        this.eventRemove.emit(data);
      }
    }
1
not make a child, < tbody>< tr> < td *ngFor="let todo of this.todos > {{todo.title}} < /td>...< /tr> - Eliseo

1 Answers

2
votes

If you want to use a child component to show the table, just call this child once, and put the ngFor loop inside that child, passing the 'this.todos' variable.

But if you are showing the table only in one place, using a child possibly doesn't make much sense, you could just loop 'this.todos' in the <tbody> and that's it.