使用方法创建对象的新实例

时间:2018-02-08 13:08:41

标签: angular angular2-changedetection

我在OnPush变化检测策略方面遇到了一些麻烦。

我有课

class Item {
  private name;
  private _valid;

  public set valid(valid) {
    this._valid = valid;
  }

  constructor(name) {
    this.name = name;
  }

  getName() {
     return this.name;    
  }
}

在我的组件中,我通过“new”运算符

创建项目的新实例
this.item = new Item('Joe'); 

并将其传递给使用OnPush策略的子组件。

<child [item]=item></child>

我在某些情况下会改变,例如有效财产

this.item.valid = false;

现在我应该创建一个新的对象实例来触发子组件中的NgOnChanges mehtod。

但我不明白,如何正确地做到这一点。

如果我this.item = {...this.item},那么项目的所有方法都会丢失。

如果我this.item = Object.create(this.item)我有空对象,所有方法和属性都在原型中。如果我做这个动作很多次原型链将每次增加一个。

或者只有一种方法 - 每次创建Item的新实例?

也许有人可以告诉我正确的方法?

1 个答案:

答案 0 :(得分:0)

您可以将类传递给子组件并调用子组件中的函数,而无需每次都创建新实例。 如果在自己的.ts文件中使用,则需要导出该类。

import { Component, Input } from '@angular/core';

@Component({
  selector: 'child',
  templateUrl: './child.component.html',
})
export class ChildComponent {
  @Input() item: Item;
}

这样称呼:

<p>{{item.getName()}}</p>

父组件:

<child [item]="item"></child>

我创建了一个简单的示例,向您展示正确执行此操作的方式:https://plnkr.co/edit/k4qBLgXxlaNkUgqU9cH5?p=preview