带有嵌套组件的bootstrap表在angular4中

时间:2017-12-15 10:12:35

标签: angular

我是angular4的初学者,我正在尝试使用嵌套组件构建bootstrap表,子组件以单行显示。 但表格显示不正确。请参阅下图

snapshot

父组件

<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);
  }

}

子组件

<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>

从&#39; ../ todo&#39;导入{Todo}; 从&#39; @ angular / core&#39;;

导入{Component,Input,Output,OnInit,EventEmitter}
@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 个答案:

答案 0 :(得分:1)

如果您想使用子组件来显示表格,只需将此孩子称为一次,然后将ngFor循环置于该子项中,并传递&#39 ; this.todos&#39;变量

但是如果你只在一个地方展示桌子,使用一个孩子可能没有多大意义,你可以循环使用这个.todos&#39;在<tbody>及其中。