Angular 5 – “无法读取未定义的属性”

前端之家收集整理的这篇文章主要介绍了Angular 5 – “无法读取未定义的属性”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Angular 5中,用于输入

<input name="techSpecMeta.make" [(ngModel)]="techSpecMeta.make" type="text" class="form-control border-input" placeholder="Enter car brand">

得到错误
无法读取未定义的属性’make’
    在Object.eval [作为updateDirectives]

export class UserComponent implements OnInit {
  constructor(private vahinfo: VehicleInfo) {}
  ngOnInit() {}
  techSpecMeta: {};
  onSave = function(vehicle,isValid: boolean) {
    this.vahinfo.saveVehicle(vehicle).subscribe(data => {
      console.log(data.data)
    },error => this.errorMessage = error)
  }
}

解决方法

techSpecMeta: {};

在类型脚本中,这意味着声明类型为{}的属性,而不初始化值.它与:

techSpecMeta: Object;

你应该这样做

techSpecMeta = {};

要使绑定工作,您还需要属性make.

techSpecMeta = {make: null};

理想情况下,您将为TechSpecMeta创建一个类/接口

class TechSpecMeta {
    make: null;
    anotherProperty: null;
}

并在您的组件中使用它

techSpecMeta = new TechSpecMeta();

猜你在找的Angularjs相关文章