如何修复TypeError:无法读取未定义的属性'trim'

时间:2019-04-04 08:20:39

标签: html angular

我正在运行我的程序,然后遇到了这个问题,该如何解决它们

HTML

<div class="form-group row">
  <label class="col-md-2 col-form-label" for="subcompanyname">Division *</label>
  <div class="col-md-3">
    <input class="form-control" type="text" placeholder="Division Name" formControlName="subcompanyname" [(ngModel)]="subcompanyDetailsOnId['name']" (keyup)="divisionExistingValidator();">
    <div *ngIf="subcompanyAdd.controls['subcompanyname'].invalid&&(subcompanyAdd.controls['subcompanyname']?.dirty ||subcompanyAdd.controls['subcompanyname']?.touched)" class="alert alert-danger">
      {{errorMessageForRequired}}
    </div>
    <div *ngIf="divisionExist" class="alert alert-danger">
      Division Already Exists
    </div>
  </div>
</div>

TypeScript

divisionExistingValidator() {
  var division = this.subcompanyAdd.controls.subcompanyname.value.trim();
  this.index = this.divisionList.findIndex(x => x.name.toLowerCase() == division.toLowerCase());
  if (this.index != -1) {
    if (this.divisionId === this.divisionList[this.index].id) {
      this.divisionExist = false;
    } else {
      this.divisionExist = true;
    }
  } else {
    this.divisionExist = false;
  }
}

错误

ERROR TypeError: Cannot read property 'trim' of undefined
    at AddSubcompanyComponent.webpackJsonp.../../../../../src/app/structure/admin/addsubcompany.ts.AddSubcompanyComponent.divisionExistingValidator (addsubcompany.ts:236)
    at Object.eval [as handleEvent] (AddSubcompanyComponent.html:33)
    at handleEvent (core.es5.js:11998)
    at callWithDebugContext (core.es5.js:13467)
    at Object.debugHandleEvent [as handleEvent] (core.es5.js:13055)
    at dispatchEvent (core.es5.js:8614)
    at core.es5.js:9228
    at HTMLInputElement.<anonymous> (platform-browser.es5.js:2648)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.es5.js:3881)

2 个答案:

答案 0 :(得分:1)

首先,您应该决定使用模板驱动形式还是反应形式。不要混在一起。

此处的其他信息: https://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/

使用反应形式

<input class="form-control" type="text" placeholder="Division Name" formControlName="subcompanyname">
// if subcompanyAdd is your form?
this.subcompanyAdd.get('subcompanyname').valueChanges.subscribe((val) => {
    if(val) {
        const division = val.trim();
        this.index = this.divisionList.findIndex(x => x.name.toLowerCase() == division.toLowerCase());
        if (this.index != -1) {
            if (this.divisionId === this.divisionList[this.index].id) {
                this.divisionExist = false;
            } else {
                this.divisionExist = true;
            }

        } else {
            this.divisionExist = false;
        }
    }
});

答案 1 :(得分:0)

尝试此方法:

 var division = this.subcompanyAdd.controls['subcompanyname'].value.trim();