如何使用 Angular 7 将数据从列表/table 绑定到模板驱动表单?

How to bind data to template driven form from a list / table using Angular 7?

Here is My code for update data.

table.Component.html

 <ng-container matColumnDef="action">
        <th mat-header-cell *matHeaderCellDef> Actions </th>
        <td mat-cell *matCellDef="let data">
          <button mat-raised-button color="primary" [matMenuTriggerFor]="menu">
            Action
          </button>
          <mat-menu #menu="matMenu">
            <a class="mat-menu-item" type="button" (click)="showForEdit(data)">Edit</a>
            <a class="mat-menu-item" type="button" href="#">Details</a>
            <a class="mat-menu-item" type="button" href="#">Delete</a>
          </mat-menu>
        </td>
</ng-container>

table.component.ts

 showForEdit(obj: any) {
    debugger;
    this.roleService.GetRoleById(obj.id)
      .subscribe(
        response => {
          this.objRoleModel = response;
          this.router.navigateByUrl("/roles/Create");
          console.log(response);

        },
        error => {
          console.log(' err ' + error);
        }
      );
  }

我的要求是我想在创建表单中从 table 获取数据以进行更新。简而言之,当我单击编辑按钮时,我想查看创建表单中填写的数据。将使用相同的表单创建和更新数据。

Here is my code for Create and Update.

form.component.html

      <form #Roleadd='ngForm' class="example-form" (ngSubmit)="CreateRole(Roleadd)">
        <h4>Role Name</h4>
        <mat-form-field class="example-full-width" appearance="outline">
          <input matInput placeholder="Enter Role" name="roleName" roleName required [(ngModel)]="objRoleModel.RoleName"
            #roleName="ngModel">
        </mat-form-field>
        <section class="section">
          <mat-checkbox name="isActive" [(ngModel)]="objRoleModel.IsActive" #isActive ="ngModel">Is Active</mat-checkbox>
        </section>
        <mat-card-actions>

            <button mat-flat-button type="submit" color="primary">Create New</button>
            <button mat-flat-button type="button" color="primary" (click)="backtolist()">Back to List</button>

        </mat-card-actions>
      </form>

form.component.ts

  CreateRole(regForm: NgForm) {

    if (regForm.value.Id == null) {

      this.objRoleModel.RoleName = regForm.value.roleName;
      this.objRoleModel.IsActive = regForm.value.isActive;

      this.roleService.CreateRole(this.objRoleModel).subscribe(res => {
        console.log(this.objRoleModel);
        alert("Role Added Successfully !!");
      })
    }
    else {

      this.roleService.updateRole(this.objRoleModel).subscribe(res => {
        alert("Role Updated Successfully !!");
      });
    }

  }

Here is my service class

Service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { RoleModel } from "../models/role.model";

@Injectable({
  providedIn: 'root'
})
export class RoleService {

  objRoleModel: RoleModel;


  constructor(private http: HttpClient) {

    this.objRoleModel = new RoleModel();
  }




  GetRoleById(Id): Observable<any> {
    debugger;
    return this.http.get("https://localhost:44336/api/Roles/" + Id)
      .pipe(
        map((response: Response) => {
          return response;
        }),
        catchError((error: Response) => {
          return throwError(console.log(error));
        })
      );
  }

  CreateRole(objRoleModel: RoleModel) {
    debugger;
    const headers = new HttpHeaders().set('content-type', 'application/json');
    var body = {
      Id: objRoleModel.Id,
      RoleName: objRoleModel.RoleName,
      IsActive: objRoleModel.IsActive
    }
    return this.http.post<RoleModel>("https://localhost:44336/api/Roles", body, { headers });

  }

  updateRole(objRoleModel: RoleModel) {
    debugger;
    const params = new HttpParams().set("Id", objRoleModel.Id.toString());
    const headers = new HttpHeaders().set('content-type', 'application/json');
    var body = {
      Id: objRoleModel.Id,
      RoleName: objRoleModel.RoleName,
      IsActive: objRoleModel.IsActive
    }
    return this.http.put<RoleModel>("https://localhost:44336/api/Roles?" + objRoleModel.Id, body, { headers, params })
  }
}

您可以使用服务在您的组件之间共享数据。在这里,我给大家分享了一个服务,它用于在单例对象中设置值和获取值。在你的模块提供者中注入这个服务,并在你的 table.component.tsform.component.ts

中声明它
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

/**
 * A singleton service to store data throughout the application lifecycle.
 *
 */
@Injectable()
export class SessionService {

  private sessionLevel: any = {};  

  setSessionVar(key: string, value: any): void {
    this.sessionLevel[key] = value;
  }

  getSessionVar(key: string): any {
    return this.sessionLevel[key];
  }
};

在您的 table.component.ts 中,点击编辑按钮时您应该设置值

 showForEdit(obj: any) {
    this.roleService.GetRoleById(obj.id)
      .subscribe(
        response => {
          this.objRoleModel = response;
          this.sessionService.setSessionVar('SELECTED_ITEM',response);
          this.router.navigateByUrl("/roles/Create");
          console.log(response);

        },
        error => {
          console.log(' err ' + error);
        }
      );
  }

在你的 form.component.ts 中,在 ngOnInit 你应该得到值

public objRoleModel: any = {};
ngOnInit() {
   if(this.sessionService.getSessionVar('SELECTED_ITEM')) {
     const data = this.sessionService.getSessionVar('SELECTED_ITEM');
     this.objRoleModel.RoleName = data.roleName;
     this.objRoleModel.IsActive = data.isActive;
   }
 }