8

我将 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函数之外运行代码,它工作得很好。

我该如何执行该代码?

4

2 回答 2

12

您正在传递对对象方法的引用,但未设置的值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必须引用组件。

于 2018-08-01T20:50:31.150 回答
1

我通过使用解决了这个问题.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>
于 2021-02-18T13:58:13.413 回答