从Angular2中的表输入中读取数据

时间:2017-06-12 23:34:06

标签: angular input html-table angular2-forms ngfor

我想创建一个包含输入的表并从中读取数据。 目前我有这个:

My table

我想分别显示每个字母,但是现在如果我输入第一行的第一个单元格,它会写入" 0":" v",第一行的第二个单元格& #34; 0":"我",......并且如我的例子所示,第一行的第五个单元格:" 0":" e",但我想拥有的是每个单元格的id,所以它必须是这样的:

"0": "v",
"1": "i",
"2": "e",
"3": "l",
"4": "e",
"5": " ",
"6": " ",
"7": " ",
...
"29": " ",

请你帮忙,我碰壁了,我不知道怎么做......

这是我的代码:

import { Component, OnInit, ViewChildren,
  Input, Directive, TemplateRef, ViewContainerRef } from '@angular/core';

import { DataService } from '../sample02-simpleService/data.service';

@Component({
  moduleId: module.id,
  selector: 'part1',
  template: `
    <div>
    <form #f="ngForm" (ngSubmit)="onSubmit(f)">
      <table>

        <tr *ngFor="let item of itemsSource; let i = index;">

          <td *biRepeat="count">
         <input name="{{i}}" ngModel #prix="ngModel" [id]="i" />
          </td>
          {{item}}
        </tr>
      </table>
    </form>
      <pre>{{f.value | json}}</pre>
    </div>


  `,
  // styleUrls: ['app/part1/part1.component.css'],
  providers: [DataService]

})
export class Part1Component implements OnInit {
  count: number;

  @ViewChildren ('prix') inputs;
  public itemsSource: string[];
  constructor(public dataService: DataService) {
    this.count = 6;
  }
  ngOnInit() {
    this.itemsSource = this.dataService.getData();
  }

@Directive({ selector: '[biRepeat]' })
export class RepeatDirective {

  constructor( private templateRef: TemplateRef<any>,
               private viewContainer: ViewContainerRef) { }
  @Input('biRepeat') set count(c: number) {
    this.viewContainer.clear();
    for (let i = 0; i < c; i ++) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    }
  }
}

1 个答案:

答案 0 :(得分:0)

首先,您需要创建一个obj键数组。然后访问该数组以获取/设置对象键的值。下面的代码在我的本地环境中使用静态数据运行良好:

import { Component } from '@angular/core';  
import { FormsModule } from '@angular/forms';


@Component({
  selector: 'my-app',
  template: `
    <ul>
        <li *ngFor="let o of obj_keys">
            <input name="o" id="o" [(ngModel)]="obj[o]" />
        </li>
    </ul>



    {{obj | json}}

  `,
  styles: [`
    ul,li{margin:0;padding:0;list-style:none;}
  `]
})

export class AppComponent  { 
    obj_keys: any; // declare empty var

    obj = {
        "0": "v",
        "1": "i",
        "2": "e",
        "3": "l",
        "4": "e",
        "5": "1",
        "6": "2",
        "7": "4"
    }

    constructor() {
        this.obj_keys = Object.keys(this.obj); // create object keys array
    }
}