Ros*_*erg 2 angular-ngselect angular
我正在对角6使用ng-select。
这是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>
Run Code Online (Sandbox Code Playgroud)
这是打字稿:
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);
}
Run Code Online (Sandbox Code Playgroud)
这是错误:
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功能则可以正常工作。
如何执行该代码?
您正在传递对对象方法的引用,但未设置的值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);
}
Run Code Online (Sandbox Code Playgroud)
然后在模板中使用该属性。
<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>
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用箭头函数将调用转发给该方法。
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);
}
Run Code Online (Sandbox Code Playgroud)
这里的要点是this必须引用该组件。
| 归档时间: |
|
| 查看次数: |
803 次 |
| 最近记录: |