微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Mat-table 通过内联编辑捕获编辑值

如何解决Mat-table 通过内联编辑捕获编辑值

我有一个 matInput 字段作为 mat-table 的单元格之一,以便可以对其进行内联编辑。此输入定义为 FormArray。

问题:当用户在表中编辑该值时,formArray 的[value] 数组没有更新。这是为什么?我想通过单击“保存配置文件”按钮来保存更新的值,即 onSaveProfile()。

请帮忙。

html 模板

  <div>
   .. selectable mat-table with all services on the left side as in screenshot

    <button mat-raised-button color="primary" type="button"
      [disabled]="selection?.selected.length <= 0"
      (click)="onAddServices()"
      >+ Add Selected Services to Profile
    </button>
  </div>

   <!-- mat-table on right side showing selected services i.e. profile -->
  <div class="w-50per" style="padding-left: 1%; align-self: flex-start;">
    <div class="mat-elevation-z8" >
      <span class="ml-1rem subTitle">Service Profile</span>
      <br><br>
      <table mat-table [dataSource]="profileDataSource" *ngIf="clientServices.length > 0">

        ......  

        <ng-container matColumnDef="fees">
          <th mat-header-cell *matHeaderCellDef> Fees </th>
          <td mat-cell *matCellDef="let row,let i=index">
            <mat-form-field>
              <input matInput [(value)]="row.fees">
            </mat-form-field>
          </td>
        </ng-container>

        ......

        <tr mat-header-row *matHeaderRowDef="serviceColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: serviceColumns;"></tr>

      </table>

    </div>
    <div class="mt-1rem">
      <button type="button" mat-raised-button color="primary"
        [disabled]="clientServices.length <= 0"
        class="mr-1rem" (click)="onSaveProfile()">Save Profile</button>
      &nbsp;
      <button type="button" mat-raised-button color="warn" (click)="onDeleteProfile()"
        [disabled]="clientServices.length <= 0"
        >Delete Profile</button>
    </div>
    <br>

  </div>

component.ts

export class EditClientServicesComponent implements OnInit,AfterViewInit {
  isLoading = false;
  id: string;

  // for all-services table on left
  totalCount = 0;
  data: Service[] = [];
  displayedColumns = ['select','servName','fees','freq'];
  selectedServices = [];
  selection: SelectionModel<Service>;

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild('input') input: ElementRef;

  // for the profile table on right
  client: Client;
  clientServices: Service[] = [];
  profileDataSource: MatTableDataSource<Service>
  serviceColumns = ['servName','freq','actions'];

  form = new FormGroup({
    serviceFees: new FormArray([])
  });
  serviceFees = this.form.get('serviceFees') as FormArray;

  constructor(
    private servicesService: ServicesService,private route: ActivatedRoute,private dialog: MatDialog
    ){}

  ngOnInit(){
    this.isLoading = true
    this.route.data.subscribe((data: Data) => {
      this.client = data['client'];
      this.clientServices = this.client.services;
      this.profileDataSource = new MatTableDataSource(this.client.services);
      this.clientServices.forEach(service => {
        this.serviceFees.push(new FormControl(service.fees))
      });
    });

    this.route.params.subscribe((params: Params) => {
      this.id = params['id'];
    });

    this.servicesService.getServices('','','asc',10)
      .pipe(
        map(recdData => {
          this.isLoading = false;
          this.totalCount = recdData.totalCount;
          return recdData.services;
        }),catchError(() => {
          this.isLoading = false;
          return observableOf([])
        })
      )
      .subscribe(services => {
        this.data = services;
        this.selection = new SelectionModel<Service>(true,[]);
      });
  }

  ngAfterViewInit() {
    .... to refresh the "all services" table
  }

  // the method to transfer selected services from the table on left to the profile table on right(see screenshot)
  onAddServices(){
    let serviceExists = false;
    this.selectedServices = this.selection.selected;
    if(this.selectedServices.length <= 0) return;

    this.selectedServices.forEach(service => {
      serviceExists = false;
      if(this.clientServices.length > 0) {
        this.clientServices.every(profile => {
          if(profile.servName == service.servName){
            serviceExists = true;
            return false;
          }
        })
        if(!serviceExists){
          this.clientServices.push(service);
          this.serviceFees.push(new FormControl(service.fees))
        }

      } else {
        this.clientServices.push(service);
        this.serviceFees.push(new FormControl(service.fees))
      }

    });
    this.profileDataSource.data = this.clientServices;
  }

  onDeleteService(index){
    let dialogRef = this.dialog.open(DeleteConfirmDialogComponent);
    dialogRef.afterClosed().subscribe(result => {
      if(result === "yes") {
        this.clientServices.splice(index,1);
        this.profileDataSource.data = this.clientServices;
        this.serviceFees.removeAt(index)
      }
    });
  }

  onSaveProfile(){
    console.log('saving profile - serviceFees',this.serviceFees)
    console.log('saving profile - services',this.clientServices)
    // you can see in screenshot that the values array of serviceFees(formArray) is not updated
    // which i was planning to use to update the fees values of clientServices array
  }

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。