Angular 6 - 无法在特定函数内 运行 外部函数

Angular 6 - Unable to run external functions inside a particular function

我正在为 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>

这是打字稿:

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

如何执行该代码?

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

我使用 .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>