我将ng-select用于角度6。
这是HTML的一面:
<ng-select [(ngModel)]="client.categoryId"
class="form-control"
[ngClass]="{'is-invalid':clientCategoryId.errors && clientCategoryId.touched}"
#clientCategoryId="ngModel"
name="categoryId"
[addTag]="addTagNow"
required>
<ng-option *ngFor="let cat of cats" [value]="cat.id">{{cat.title}}</ng-option>
</ng-select>
这是打字稿:
nCategory: Category = {
title: ''
};
constructor(public afs: AngularFirestore) {
this.categoriesCollection = this.afs.collection('categories', ref => ref.orderBy('title', 'asc'));
}
addTagNow(name) {
this.nCategory.title = name;
this.categoriesCollection.add(this.nCategory);
}
这是错误:
NgSelectComponent.html:91 ERROR TypeError: Cannot set property 'title' of undefined
at NgSelectComponent.push../src/app/components/edit-client/edit-client.component.ts.EditClientComponent.addTagNow [as addTag] (edit-client.component.ts:169)
如果我在AddTagNow
函数之外运行代码,则可以正常工作。
如何执行该代码?
答案 0 :(得分:4)
您正在传递对对象方法的引用,但是未设置this
的值。因此,您需要bind(this)
到函数引用。
public addTagNowRef: (name)=>void;
constructor(public afs: AngularFirestore) {
this.categoriesCollection = this.afs.collection('categories', ref => ref.orderBy('title', 'asc'));
this.addTagNowRef = this.addTagNow.bind(this);
}
然后在模板中使用该属性。
<ng-select [(ngModel)]="client.categoryId"
class="form-control"
[ngClass]="{'is-invalid':clientCategoryId.errors && clientCategoryId.touched}"
#clientCategoryId="ngModel"
name="categoryId"
[addTag]="addTagNowRef"
required>
<ng-option *ngFor="let cat of cats" [value]="cat.id">{{cat.title}}</ng-option>
</ng-select>
或者,您可以使用箭头函数将调用转发给该方法。
public addTagNowRef: (name)=>void;
constructor(public afs: AngularFirestore) {
this.categoriesCollection = this.afs.collection('categories', ref => ref.orderBy('title', 'asc'));
this.addTagNowRef = (name) => this.addTagNow(name);
}
这里的意思是this
必须引用该组件。
答案 1 :(得分:0)
我使用 .bind(this)
解决了这个问题:
<ng-select [(ngModel)]="client.categoryId"
class="form-control"
[ngClass]="{'is-invalid':clientCategoryId.errors && clientCategoryId.touched}"
#clientCategoryId="ngModel"
name="categoryId"
[addTag]="addTagNow.bind(this)"
required>
<ng-option *ngFor="let cat of cats" [value]="cat.id">{{cat.title}}</ng-option>
</ng-select>