angular - 将行的数据从 table 组件传递到带有编辑按钮的表单组件

我正在使用 Angular,任何人都可以帮我举一个从 table 组件的行中传递数据并使用编辑按钮将其显示在另一个表单组件中的示例。

我尝试通过使用 BehaviorSubject 来为此使用服务。

发射.service.ts

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

public defaultValue : string = '';
public RowSender : BehaviorSubject<string>= new BehaviorSubject<string>(this.defaultValue);
public currentValueEmit = this.RowSender.asObservable();


public sendValue(RowtoEmit:string){

this.RowSender.next(RowtoEmit);

}

public recieveValue():Observable<string>{
    return this.RowSender.asObservable();
}  
   
   
  constructor() { }
}

Tier.Component.ts(这是 table 组件)

constructor(private router: Router,private _EmitService :EmitService){}

//this the button for editing in table actions' column

edit(value : any)
    {
     this._EmitService.sendValue(value.id);
     this._EmitService.sendValue(value.raisonSociale);
     this._EmitService.sendValue(value.nomComplet);
     this._EmitService.sendValue(value.adresse);
     this.router.navigateByUrl('referencielcommun/Tier/Form');
    }

Form.Component.ts

constructor(private _EmitService : EmitService) {

      this._EmitService.recieveValue().subscribe(
        (d:any)=>{
          {
          this.TierForm.controls['ID'].setValue(d.id);
          this.TierForm.controls['NomComplet'].setValue(d.raisonSociale ?? null);
          this.TierForm.controls['NomComplet'].setValue(d.nomComplet ?? null);
          this.TierForm.controls['Adresse'].setValue(d.adresse ?? null);
  
        }}); 
     }

Form.component.html

<form [formGroup] ="TierForm" class="form-inline" (ngSubmit)="onFormSubmit()" >
      <fieldset>
      <legend>Formulaire de Tier</legend>
    
   <div class="container">
      <div class="row" >
        
        <div class="col-xs-12 col-md-4">
          <div style="display: flex;flex-direction: column;">
            <mat-label><strong> Raison Sociale :</strong></mat-label>
            <mat-form-field class="example-full-width" appearance="fill">
              <input matInput ngModel formControlName="RaisonSociale">
              <mat-error *ngIf="true">
                Ce Champs est obligatoire.
              </mat-error>
            </mat-form-field>
          </div>
        </div>
      
      <div class="col-xs-12 col-md-4">
        <div style="display: flex;flex-direction: column;">
          <mat-label><strong> Nom complet :    </strong> </mat-label>
          <mat-form-field class="example-full-width" appearance="fill">
            <input matInput ngModel formControlName="NomEtPrenom">
          </mat-form-field>
         </div>
      </div>
      
      <div class="col-xs-12 col-md-4">
        <div style="display: flex;flex-direction: column;">
          <mat-label><strong> Adresse :    </strong> </mat-label>
          <mat-form-field class="example-full-width" appearance="fill">
            <input matInput ngModel formControlName="Adresse">
            <mat-error *ngIf="true">
              Ce Champs est obligatoire.
            </mat-error>
          </mat-form-field>
        </div>
      </div>
  
  <div class="center">
      <button class="addbutton" mat-raised-button color="primary" type="submit"  style="justify-content: left !important;">{{actionBtn}}</button>
      <button class="addbutton" mat-raised-button color="warn" (click)="Annuler()"  style="justify-content: left !important;">Annuler</button>
    </div>
     </fieldset>
    </form>

回答1

您可以尝试在方法中获取数据,然后通过服务将其传递给您的自定义组件

回答2

现在从头开始后解决了。

首先,我们创建了一个发射器服务,以便在两个组件之间发送和接收数据。

发射.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

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

//we have to set an empty defaultValue for the TableRow
  public defaultValue : string = '';
  public TableRow : BehaviorSubject<string>= new BehaviorSubject<string>(this.defaultValue);


  public sendValue(RowtoEmit:string){
    this.TableRow.next(RowtoEmit);}

  public recieveValue():Observable<string>{
      return this.TableRow.asObservable();}  

  constructor() { }
}

然后我们前往 Table 组件,当然我们将从那里将数据发送到表单组件。

table.component.ts

// we declare the router and the Emit service in the constructor

  constructor(private router: Router,private _EmitService :EmitService){

// we add a method for the edit button on table

  edit(value : any)
    {

      this._EmitService.sendValue(value);
      this.router.navigateByUrl('referencielcommun/Tier/Form');
    }
}

现在我们必须使用 (click)="edit(row)" 从 table 中获取行数据

table.component.html

<ng-container matColumnDef="ACTION" >
            <th mat-header-cell *matHeaderCellDef mat-sort-header class="actionheader"> Action</th>
            <td mat-cell *matCellDef="let row">
          
            <button mat-icon-button color="primary" type="button" (click)="edit(row)">
              <mat-icon>edit</mat-icon>
            </button>   
            </td>
          </ng-container>

然后我们前往我们的表单组件,在那里我们将接收我们的数据并在输入中显示它们。

form.component.ts

TierForm:any = this.formBuilder.group({
    ID:[0],
    RaisonSociale:[null,[Validators.required]],
    NomEtPrenom:[null],
    Adresse:[null,[Validators.required]],
  });

// we declare the router & the emit service as well in the constructor

constructor(private router : Router,private _EmitService : EmitService){

/* in the body of the constructor we set the values of the data recieved from 
our row in the form inputs*/


      this._EmitService.recieveValue().subscribe(
        (d:any)=>{
          if(d != null)
          {
          this.TierForm.get('ID').setValue(d.id ?? 0);
          this.TierForm.get('RaisonSociale').setValue(d.raisonSociale ?? null);
          this.TierForm.get('NomEtPrenom').setValue(d.nomEtPrenom ?? null);
          this.TierForm.get('Adresse').setValue(d.adresse ?? null);
        }}); 

}

最后我们放上我们的表单控件。

form.component.html

<div class="col-xs-12 col-md-4">
          <div style="display: flex;flex-direction: column;">
            <mat-label><strong> Raison Sociale :</strong></mat-label>
            <mat-form-field class="example-full-width" appearance="fill">
              <input matInput  [formControl]="TierForm.get('RaisonSociale')">
              <mat-error *ngIf="true">
                Ce Champs est obligatoire.
              </mat-error>
            </mat-form-field>
          </div>
        </div>
      
       <div class="col-xs-12 col-md-4">
        <div style="display: flex;flex-direction: column;">
          <mat-label><strong> Nom complet :    </strong> </mat-label>
          <mat-form-field class="example-full-width" appearance="fill">
            <input matInput [formControl]="TierForm.get('NomEtPrenom')">
          </mat-form-field>
         </div>
      </div>
      
      <div class="col-xs-12 col-md-4">
        <div style="display: flex;flex-direction: column;">
          <mat-label><strong> Adresse :    </strong> </mat-label>
          <mat-form-field class="example-full-width" appearance="fill">
            <input matInput  [formControl]="TierForm.get('Adresse')">
            <mat-error *ngIf="true">
              Ce Champs est obligatoire.
            </mat-error>
          </mat-form-field>
        </div>
      </div>

请记住,即使您导航到另一个组件,BehaviourSubject 也会保存 value,这就是为什么您必须将发送的 value 设置为 '' 或 null 如果您已完成使用它。

相似文章