我正在运行我的程序,然后遇到了这个问题,该如何解决它们
<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>
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)
答案 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();