如何在html表和angular 2组件之间实现2路数据绑定

时间:2017-03-01 18:48:21

标签: javascript html angular

我有一个使用* ngFor指令填充的表。用户可以单击表中的每个单元格,并根据“contentEditable”属性编辑其值。当前实现更新表中的数据,但不更新组件中的数据。当用户使用native 2的工具更改单元格中的数据时,是否可以更新组件中的数据?如果是这样,怎么样?

这是html文件:

<table id="data-table" class="table table-striped">
    <thead>
      <tr>
        <th *ngFor="let round of rounds">{{ round.title }}</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let player of players">
        <td contenteditable="true">{{ player.name }}</td>
        <td contenteditable="true">{{ player.round1 }}</td>
        <td contenteditable="true">{{ player.round2 }}</td>
        <td contenteditable="true">{{ player.round3 }}</td>
      </tr>
    </tbody>
  </table>

这是组件:

import { Component, OnInit } from '@angular/core';
import { BooksAndRunService } from '../books_and_run.service';



@Component({
  moduleId: module.id,
  selector: 'books-and-run-play',
  templateUrl: './books_and_run_play.component.html',
  styleUrls: ['./books_and_run_play.component.css'],
})


export class BooksAndRunPlayComponent implements OnInit {
  constructor(private booksAndRunService: BooksAndRunService) { }
  currentRound = 1;

  rounds = [
    {title: ""},
    {title: "Round 1"},
    {title: "Round 2"},
    {title: "Round 3"},
    {title: "Round 4"},
    {title: "Round 5"},
    {title: "Round 6"},
    {title: "Round 7"},
  ]

  players = [
    {
      name: "Bob",
      round1: 0,
      round2: 0,
      round3: 0,
      round4: 0,
      round5: 0,
      round6: 0,
      round7: 0,
    },
    {
      name: "Joe",
      round1: 0,
      round2: 0,
      round3: 0,
      round4: 0,
      round5: 0,
      round6: 0,
      round7: 0,
    },
    {
      name: "Jim",
      round1: 0,
      round2: 0,
      round3: 0,
      round4: 0,
      round5: 0,
      round6: 0,
      round7: 0,
    },
    {
      name: "Sarah",
      round1: 0,
      round2: 0,
      round3: 0,
      round4: 0,
      round5: 0,
      round6: 0,
      round7: 0,
    },
    {
      name: "Jane",
      round1: 0,
      round2: 0,
      round3: 0,
      round4: 0,
      round5: 0,
      round6: 0,
      round7: 0,
    },
    {
      name: "Jill",
      round1: 0,
      round2: 0,
      round3: 0,
      round4: 0,
      round5: 0,
      round6: 0,
      round7: 0,
    },
  ];



  ngOnInit(): void {
    // this.players = this.booksAndRunService.getPlayers();

  }

}

1 个答案:

答案 0 :(得分:1)

使用contenteditable =&#34; true&#34;您没有获得ngModel属性,因此您需要创建自己的双向数据绑定:

<td contenteditable="true" [textContent]="player.name"   (input)="player.name = $event.target.textContent"></td>

或者你也可以这样做

<td contenteditable="true" [textContent]="player.name"   (input)="onContentChanged($event)"></td>

然后在你的组件类

onContentChanged(event : Event)
    {
        let playerName : string = event.target.textContent;

        .... Do stuff here ....
    }
相关问题