且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在angular 6表单构建器中找不到具有未指定名称属性的控件

更新时间:2023-12-06 13:20:58

我认为主要问题在这里

<input type="text" [formControlName]="vin" ><br><br>

您尝试传递一个空变量

vin: any;

作为控件名称,可以通过以下方式固定:

as control name, this can be fixed in this way:

<input type="text" formControlName="vin" ><br><br>

只需移除方括号并将控件名称设置为字符串即可.

just remove square brackets and set control name as string.

它应该解决您的问题.

这部分

  this.activatedRoute.paramMap
.subscribe( params => {
this.id = +params.get('id');
});

  this.vehicle.forEach(element => {
    if (element.id === this.id) {
        this.Data = element;
          }
  });
  this.myvehicle.patchValue({
    vin: this.Data.vin,
    year: this.Data.year,
    brand: this.Data.brand,
    color:  this.Data.color
  });

可以简化

    this.activatedRoute.paramMap
  .subscribe(params => {
    const id = params.get('id');

    if (this.vehicle[id]) {
      this.myvehicle.patchValue(this.vehicle[id]);
    }
  });

仅当您在路由器参数中具有正确的ID时,patchValue才会运行

here patchValue runs only when you have a correct id in router params