首页 > 解决方案 > 无法读取未定义的属性“单位”

问题描述

我创建了一个有角度的模板驱动形式。但是我收到错误,因为无法读取未定义的属性“单位”。我也创建了模型。并且也在 ts 文件中定义。仍然收到此错误。请提供任何帮助。

用户选择.component.html

<form name="form" #f="ngForm" class="form-horizontal">
  <div class="border mt-2  p-2 pt-4">
    <div class="form-row">
      <div class="form-group col-md-12">
        <label for="units">
       Please specify the number of units being used: &nbsp;&nbsp;</label>
       <input type="number" min="1" max="12" class="col-sm-2 pr-0 pl-0 col-form-label" [(ngModel)]="userChoice.units.value" name="units"  >
      </div>
    </div>
</form>

用户选择.component.ts

import { Component, OnInit ,Input} from '@angular/core';
import { UserChoice } from './user-choice.model';

@Component({
  selector: 'app-user-choice',
  templateUrl: './user-choice.component.html',
  styleUrls: ['./user-choice.component.css']
})
export class UserChoice implements OnInit {

  constructor() { }
  userChoiceModel: UserChoiceModel;


  @Input() unitBase:any;


  ngOnInit() {
  }

}

用户选择.model.ts

import { BasicSearchModelI } from '../../../../../core/base';

export class UserChoiceModel {
      units: BasicSearchModelI = {
            value: ''

      };
      qty: BasicSearchModelI = {
            value: ''

      };
      desc: BasicSearchModelI = {
            value: ''

      };

}

标签: angular

解决方案


您的模型名称是userChoiceModel,但在您的模板中,您使用的是userChoice. 您需要ngModel[(ngModel)]="userChoiceModel.units.value".

现在您需要做的就是userChoiceModel在您的组件中进行初始化。您所做的只是给它一个类型,但它的值仍然是undefined. 你可以像这样初始化它

userChoiceModel: UserChoiceModel = new UserChoiceModel();

推荐阅读