【问题标题】:Angular2 ngOnChanges clone @Input arrayAngular2 ngOnChanges 克隆 @Input 数组
【发布时间】:2017-01-12 15:24:34
【问题描述】:

我正在使用DashboardComponent 从我的DashboardService 获取数据。然后这个组件将我的对象数组传递给我的表单组件。

(帖子底部的Plunkr链接)

DashboardComponent.ts

 private bottleArray: Bottle[] = [];

  ngOnInit() {
    // Get bottle types from service to the form needing them
    this.dashboardService.getBottleTypesAndNames()
      .subscribe(bottlesData => {
        bottlesData.forEach(bottle => {
          // Convert to Bottle type
          let bottleObject: Bottle = new Bottle(bottle.bottleTypeId, bottle.bottleName);
          this.bottleArray.push(bottleObject);
        });
      });
  }

DashboardComponent.html

<ct-create-order-form [bottleArray]="bottleArray"> </ct-create-order-form>

我这样做是为了让链接到我的Dashboard 的表单组件不会调用我的服务。

我正在尝试clone我的@Input,以便我从表单更新的数据未链接到我的父组件(仪表板),但我似乎无法做到这一点......见下面的代码:

CreateOrderFormComponent.ts

export class CreateOrderFormComponent implements OnChanges {
  @Input() private bottleArray: Bottle[];

  constructor() { }

  private clonedBottleArray: BottleCommand[];

  ngOnChanges(changes) {

    if (changes.bottleArray) {
      let test: BottleCommand[] = changes.bottleArray.currentValue;

      // Cloning
      console.log(test);  // Array of 6 Bottles

      this.clonedBottleArray = [...test];       
      console.log(this.clonedBottleArray);         // Empty Array
      this.clonedBottleArray = Array.from(test);
      console.log(this.clonedBottleArray);         // Empty Array
      this.clonedBottleArray = test.slice();
      console.log(this.clonedBottleArray);         // Empty Array

      this.clonedBottleArray = test;
      console.log(this.clonedBottleArray);         // Array of 6 bottles
   }
}

有什么方法可以实现我正在做的事情吗?我不明白为什么我在获取数据时无法克隆我的输入?

从 AngularConnect 制作的这个 Youtube 视频中,他正在做同样的事情,只是他正在操作一个对象,而我正在操作一个对象数组。

https://youtu.be/-nsedZwvl9U?t=12m22s


编辑:创建 Plunkr 后,这似乎在那里正常工作。

https://plnkr.co/edit/js1vl0fcgOKtQNqXsWTL?p=preview


EDIT 2:在我的DashboardComponentngOnInit(),如果我模拟数据,它会正确克隆到我的子组件中。

【问题讨论】:

    标签: arrays angular ecmascript-6 clone ngonchanges


    【解决方案1】:

    由于特定的检查方式,角度 OnChange 似乎没有触发,这里是来自 this answer 的简要说明:

    在更改检测期间,当 Angular 检查组件的输入属性是否有更改时,它(本质上)使用 === 进行脏检查。对于数组,这意味着(仅)对数组引用进行了脏检查。由于 rawLapsData 数组引用没有改变,ngOnChanges() 不会被调用。

    在您的示例中,您是.pushbottleArray 中的瓶子,因此 OnChange 不会在同一个数组引用上触发。

    要获得更改,您可以使用DoCheck:

    ngDoCheck() {
      console.log(this.bottleArray);
      this.clonedBottleArray = [...this.bottleArray].slice(0, 4);
      console.log(this.clonedBottleArray);
    }
    

    当您将新值推送到bottleArray 时,它将触发。工作的笨蛋here.

    【讨论】:

    • 感谢您的调查,但这并没有真正为我提供解决方案...我将编辑我的帖子,我有关于该问题的新信息
    • @AlexBeugnet,好吧,看来我找到了问题,更新了我的答案。
    • 是的,我也刚刚发现了这一点。这就是问题所在。谢谢!
    猜你喜欢
    • 2018-09-28
    • 2015-02-12
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-17
    • 1970-01-01
    相关资源
    最近更新 更多