Angular 5-从表单更新模型

时间:2018-06-29 14:02:50

标签: forms angular5 updates crud

我是Angular 5的新手,我正在尝试制作CRUD。 我正在努力处理“更新”部分。

我想做的是,在我的表单中,获取模型的数据以填充输入文本,然后,当我单击更新按钮时,更新所有模型。

我在tut和论坛上尝试了很多东西,但现在我完全迷失了。这就是我所拥有的。

html:

<form [formGroup]="policyForm" (ngSubmit)="update()">
  <mat-form-field>
    <input formControlName="policyName">
  </mat-form-field>
... Many other inputs
  <button type="submit" color="primary">Update</button>
</form>

组件:

export class PolicyUpdateComponent implements OnInit {

  policyModel: PolicyModel;
  policyId = +this.route.snapshot.paramMap.get('id');
  policyForm: FormGroup;
  formBuilder: FormBuilder;

  constructor(

    private policyService: PolicyService,
    private route: ActivatedRoute,
    private router: Router,
    private fb: FormBuilder

  ) {

    this.policyService.get(this.policyId)
      .subscribe(policy => this.policyModel = policy);
  }


  ngOnInit() {
    this.createForm();
  }

  createForm() {
    this.policyForm = this.fb.group({
      policyName: [this.policyModel.name, Validators.required]
    });
  }

  update(id: number) {
    id = this.policyId;
    this.policyModel = <PolicyModel>this.policyForm.value;
    this.policyService.update(id, this.policyModel).subscribe(res => {
      this.router.navigate(['/policies', id, 'get']);
    }, (e) => {
      console.log(e);
    }
    );

  }

}

服务:

 /**
   * Update a policy with new parameters
   * @param pm PolicyModel
   */
  update(id: number, pm: PolicyModel): Observable<any> {
    return this.http.put<PolicyModel>(`${environment.baseApiUrl}/${environment.apiVersion}/policies/${id}`, {pm});
  }

任何帮助都很好。.谢谢大家!

1 个答案:

答案 0 :(得分:1)

根据此更改代码。

<form [formGroup]="policyForm"  >
  <mat-form-field>
    <input formControlName="policyName">
  </mat-form-field>
  <button color="primary" (click)="update()">Update</button>
</form>

添加订阅以检测表单更改。

    ngOnInit() {
        this.createForm();

        this.policyForm.valueChanges.subscribe(
          (data) => {
            if (JSON.stringify(data) !== JSON.stringify({})) {
              this.policyModel.name = data.policyName;
            }
          });
      }

      createForm() {
        this.policyForm = this.fb.group({
          policyName: [this.policyModel.name]
        });
      }

       update(id) {
       this.policyModel.id = id;
       id = this.policyId;
   this.policyService.update(id, this.policyModel)//.subscribe(res => {
     this.router.navigate(['/policies', id, 'get']);
    }, (e) => {
      console.log(e);
    }
    );
      }

示例代码:https://stackblitz.com/edit/angular-wwt91u