【问题标题】:Bootstrap table with nested components in angular4带有嵌套组件的引导表 angular4
【发布时间】:2018-05-29 12:42:35
【问题描述】:

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

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>

从 '../todo' 导入 { Todo }; 从'@angular/core'导入{组件、输入、输出、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);
      }
    }

【问题讨论】:

  • 不要生孩子, {{todo.title}} ...

标签: angular


【解决方案1】:

如果您想使用子组件来显示表格,只需调用此子组件一次,然后将 ngFor 循环放入该子组件,并传递 'this. todos 的变量。

但是,如果您只在一个地方显示表格,使用孩子可能没有多大意义,您可以在 &lt;tbody&gt; 中循环“this.todos”,仅此而已。

【讨论】:

    猜你喜欢
    • 2017-09-16
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 2012-10-12
    相关资源
    最近更新 更多