使用模板驱动的Angular 6中创建和编辑数据的相同形式

问题描述 投票:1回答:1

有2个组件。在DashboardComponent中有一个已创建表单的列表,在CreateFormComponent中,我需要对正在DashboardComponent中显示的已创建表单执行添加和编辑操作。两个操作都将使用相同的表单。我可以根据特定ID从DashboardComponent导航到CreateFormComponent但不能对其执行编辑操作。代码:dashboard.html

<tr 
  *ngFor="let user of users" 
  style="text-align: center;">
  <button 
    mat-mini-fab 
    style="background: white !important;color:black !important;outline:none;" 
    [routerLink]="['/Create_form',user.id]">
        <!--<i class="fa fa-edit" aria-hidden="true"></i>-->
    Edit
  </button>
</tr>

Create_Form:

<form 
  #spfForm="ngForm" 
  (ngSubmit)="createspf(spfForm.value)" 
  ngNativeValidate>
  <mat-form-field style="margin-top:-6%;">
    <mat-select 
      [(ngModel)]="Priority" 
      name="Priority" 
      placeholder="Priority">
      <mat-option value="High">
        High
      </mat-option>
      <mat-option value="Medium">
        Medium
      </mat-option>
      <mat-option value="Low">
        Low
      </mat-option>
    </mat-select>
  </mat-form-field>
</form>

Create_form.component.ts:

createspf(value) {
  this.userservice.spf(value).subscribe((res: Response) => [
    this.IsAdded = true,
    console.log(this.confirmationString)
  ]);
}
angular angular-material
1个回答
2
投票

既然你没有真正提供StackBlitz而且我没有时间为你创建一个完整的Form Stackblitz,我建议你这样做:

在你的CreateFormComponent中,在ngOnInit()中,使用FormBuilder初始化ReactiveForm,或者使用FormGroupFormControls手动创建一个。

同时在这个组件中注入ActivatedRoute并订阅activatedRouterInstanceparams BehaviorSubject。如果有来自那里的任何id,请通过该ID获取该项目的详细信息,并通过调用setValuepatchValue填充您创建的表单。

如果是Create,由于params中没有任何id,用户只会看到一个空表单。但是在编辑的情况下,由于将实现表单的值,用户将看到填充了所获得的数据的表单。

希望能有所帮助并帮助你。

© www.soinside.com 2019 - 2024. All rights reserved.