2017-06-12 54 views
0

我想創建一個帶有輸入的表格並從中讀取數據。 目前,我有這樣的:從Angular2的表格輸入中讀取數據

My table

我想單獨顯示每個字母,但現在如果我在第一排的第一個單元格中鍵入,它寫道:「0」:「V」,第二單元第一行「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); 
    } 
    } 
} 

回答

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 
    } 
} 
+0

謝謝你,但我需要顯示類似的obj =數據{」‘0’:‘V’,‘1’:‘我’},我從數組中獲取數據並在Dataservice中定義(在提供者中),有5個單詞,我希望能夠使每個輸入具有唯一性並從每個輸入數據中讀取,此刻我可以從每行讀取數據,不是細胞... – Natali