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

时间:2019-02-23 07:38:42

标签: angular angular-material-6

  

这是我的更新数据代码。

table.Component.html

type song struct {
    Id      int
    Artist  string
    Picture string
    Name    string
}

type data struct {
    Songs []song
}

db, err := sql.Open(sqlServer, sqlData)
checkErr(err)

rows, err := db.Query("SELECT s.id, a.name a_name, al.picture, s.song_name FROM music_songs s JOIN music_albums al ON s.album_id = al.id JOIN music_artists a ON a.id = s.artist_id WHERE s.artist_id = ? ORDER BY s.id ASC, al.id ASC", ar)
checkErr(err)

var songs []song
for rows.Next() {
    var id int
    var artist string
    var picture string
    var name string

    err = rows.Scan(&id, &artist, &picture, &name)
    songs = append(songs, song{id, artist, picture, name})
}

fmt.Println(songs)

table.component.ts

+----+---------+---------+--------------------------+
| id | a_name  | picture | song_name                |
+----+---------+---------+--------------------------+

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

  

这是我创建和更新的代码。

form.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>

form.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);
        }
      );
  }
  

这是我的服务班

Service.ts

      <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>

1 个答案:

答案 0 :(得分:2)

您可以使用服务在组件之间共享数据。在这里,我为您共享了一项服务,该服务用于设置值和获取Singleton对象中的值。将此服务注入模块的提供程序中,并在 table.component.ts form.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;
   }
 }