单击编辑按钮时如何在表单中显示行数据(角度8)

时间:2019-09-21 08:45:43

标签: angular

当我单击特定表行上的编辑按钮时,我希望行数据显示在表单字段中,我只有一个(1)组件,并且我的表和表单都在同一个component.html中。我该如何运作?

请参阅下面的代码示例:

component.html

<tr *ngFor="let myCar of cars$ | paginate: { itemsPerPage: count, currentPage: p }; let i = index">
            <td>{{ (p - 1) * count + i + 1 }}</td>
            <td>{{myCar.name}}</td>
            <td>{{myCar.price}}</td>
            <td><button type="submit" class="btn btn-secondary" (click)="">
                    <i class="glyphicon glyphicon-edit"></i>Edit
                </button></td>
</tr>
<div class="col-sm-12">
        <form formGroup="editForm" autocomplete="off">
            <h4 align="center">
                <strong>Edit Car</strong>
            </h4>
            <div class="form-group">
                <label>Name:</label> <input type="text" class="form-control" formControlName="name">
            </div>
            <div class="form-group">
                <label>Price:</label> <input type="text" class="form-control" formControlName="price">
            </div>
            <button class="btn btn-secondary">
                <i class="glyphicon glyphicon-floppy-save"></i>Save
            </button>
        </form>
</div>

service.ts

....
// requesting data via http
getCars() {
   return this.http.get<Cam[]>(this.carsUrl);
}

component.ts

// imports
......
editForm: FormGroup;

constructor(...){...}

ngOnInit() {
   carList();
   carEditInit();
}
carList() {
   return this.carService.getCars()
     .subscribe(data => {
        this.cars$ = data;
   });
}

// I just initialised the form fields
carEditInit() {
   this.editForm = this.fb.group({
     name: [''],
     price: ['']
   )};
}

如何使这些代码起作用,或.ts文件中的哪些附加内容,以便在单击“编辑”按钮后将数据发送到表单字段。 我在同一个component.html中都有* ngFor表和表单

谢谢

1 个答案:

答案 0 :(得分:0)

将事件分配给函数,并将其myCar对象传递给单击编辑按钮的行

<tr *ngFor="let myCar of cars$ | paginate: { itemsPerPage: count, currentPage: p }; let i = index">
            <td>{{ (p - 1) * count + i + 1 }}</td>
            <td>{{myCar.name}}</td>
            <td>{{myCar.price}}</td>
            <td><button type="submit" class="btn btn-secondary" (click)="fillForm(myCar)">
                    <i class="glyphicon glyphicon-edit"></i>Edit
                </button></td>
</tr>

在.ts文件中,定义函数并使用setValue()设置表单字段:

fillForm(myCar)
{
   this.editForm.controls.name.setValue(myCar.name);
   // ... Do the same for rest of your form fields

  this.editForm.updateValueAndValidity(); //Update the values for all fields
}