从json
文件获取数据后,我将数据分配给组件中存在的数组,并使用*ngFor
将该数组循环到表中。
现在我有了一个按钮,使用该按钮,我在表中添加一行(实际上是将一个对象添加到与表绑定的数组中),并带有空字段。在这里,我使用的是<x-editable>
组件,它将数据从空编辑为表中有意义的内容。编辑后,我想将数据存储到组件中的newAttr
对象中。但是如何将td
的数据与newAttr
对象绑定。她是我的代码
app.component.html
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Rank</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let d of data">
<td><x-editable>{{d.id}}</x-editable></td>
<td><x-editable>{{d.name}}</x-editable></td>
<td><x-editable>{{d.rank}}</x-editable></td>
</tr>
</tbody>
</table>
<br>
<button (click)="addStudent()">Add A Student</button>
app.component.ts
import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
data : any = [];
newAttr : any = [];
constructor(private http: Http){
}
ngOnInit(){
this.http.get('./assets/students.json').subscribe(data=>{
this.data = data.json().data;
})
}
addStudent(){
this.newAttr = {id:"empty",name:"empty",rank:"empty"};
this.data.push(this.newAttr);
this.newAttr = {};
}
}
students.json(我不认为它需要但仍然......)
{
"data":[
{
"id":101,
"name":"Andrew",
"rank":3
},{
"id":102,
"name":"Bob",
"rank":5
},{
"id":103,
"name":"James",
"rank":1
},{
"id":104,
"name":"Matthew",
"rank":2
},{
"id":105,
"name":"Kevin",
"rank":4
}
]
}
答案 0 :(得分:0)
you can use **@Output()** decoration in your child component
**@Output() rowdata = new EventEmitter<any>();** and emit edit data like below
**this.rowdata.emit(editdata);**
than use this @Output in your parent like
<td><x-editable (rowdata)="geteditdata($event)">{{d.id}}</x-editable></td>
your child component edit data get in geteditdata() function like below
geteditdata(editdata){
//here you bind edit data in your newAttr object by unique id
}