且构网

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

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

更新时间:2023-10-22 10:03:34

我觉得主要问题在这里

<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.

它应该可以解决您的问题.

it should fix your issue.

还有这部分

  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]);
    }
  });

此处 patchValue 仅在路由器参数中具有正确 id 时运行

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