角度2无法读取未定义的属性 [英] angular 2 cannot read property of undefined

查看:115
本文介绍了角度2无法读取未定义的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误

无法读取未定义的属性值"

Cannot read property 'value' of undefined

下面是我的代码

<select class="form-control form-control-lg" formControlName="contractor" (ngModelChange)="onChange($event.target.value)" >
                    <option *ngFor="let contrac of contractors" [ngValue]="contrac">{{contrac.name}}</option>
                </select>

 <label class="control-label col-lg-2">Agency</label>
            <div class="col-lg-10">
                <input type="text" class="form-control form-control-lg" placeholder="Payroll Number" formControlName ="selectedAgency">
            </div>

组件

 ngOnInit() {
        this.form = this.fb.group({
            agency: ['', Validators.required],
            contractor: ['', Validators.required],
            selectedAgency : ['', Validators.required]

        });

 onChange = (contrac) => {
        alert(contrac.vendor);
        this.form.patchValue({ selectedAgency: contrac.vendor });
    }

这里有什么错过的地方吗?

Is there anything that missed out here?

-艾伦-

推荐答案

应为:

(ngModelChange)="onChange($event)"

...或尚未使用(更改):

(change)="onChange($event.target.value)"

但是,似乎您只是在使用它为表单中的另一个控件设置一个值,对吧?

But, seems like you're only using this to set a value for another control in form, right?

因此,可以在要设置值的输入上使用 [ngModel] ,如下所示:

So, you can use [ngModel] on the input that you want to set the value, as below:

<select class="form-control form-control-lg" formControlName="contractor">
  <option *ngFor="let contrac of contractors" 
          [ngValue]="contrac">{{contrac.name}}</option>
</select>

<label class="control-label col-lg-2">Agency</label>
<div class="col-lg-10">      
  <input type="text" 
         class="form-control form-control-lg" 
         placeholder="Payroll Number" 
         formControlName ="selectedAgency" 
         [ngModel]="myForm.get('contractor').value.vendor">
</div>

这篇关于角度2无法读取未定义的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆