【问题标题】:Angular child component does not recognize change in input propertyAngular 子组件无法识别输入属性的变化
【发布时间】:2020-12-11 16:36:01
【问题描述】:

我有一个父组件,它拥有一个名为文档的属性。该属性是一个数组,用于将数组中的文档传递给子组件。

但是当我将一个新文档推送到我的属性文档中时,子组件的视图并没有改变。有人可以告诉我在这里做错了什么吗?

这是我在父组件中属性文档发生变化的地方:

 // handle the data that comes back from the dialog
 createDialog.afterClosed().subscribe(
  data => {
    if (data){

      // persist vital signs
      this.documentService.saveDocument(data.newDocument); // not implemented yet because it makes no sense with non functioning backend

      this.documents.push(data.newDocument);

      // update the existing document bucket the document belongs to
      this.loincToDocumentsMap.get(data.loincCode)?.folderContent.push(data.newDocument);

    }
  }
);

这是我的子组件:

@Component({
  selector: 'document-list',
  templateUrl: './document-list.component.html',
  styleUrls: ['./document-list.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class DocumentListComponent implements OnInit, OnChanges {

  @Input() documents: DocumentReference[] = [];
  
  ....
}

这就是我在父组件中使用子组件的地方:

<document-list *ngIf="showListUi" [documents]="documents"></document-list>

我真的很感激一些帮助,因为其他组件也一样,我看不出有任何区别。例如,位于同一父组件中的另一个子组件正在正确更新。

更新 1:

添加后,更改检测工作。但为什么呢?

this.documents = this.documents.filter(document => {
        return true;
      })

更新 2: 谢谢大家,解决方案在答案中:)

【问题讨论】:

  • 1.控制台中的任何错误? 2. FOA,showListUi 是否设置为 true?
  • 是的。不幸的是,控制台中没有错误。但我想我知道会发生什么。 Angular 似乎没有检测到文档数组中的变化。我刚刚添加了一个完整的废话代码行:我在最初的帖子中添加了一个更新,显示了我添加的内容* 现在更改检测按预期工作。但为什么呢?

标签: angular typescript


【解决方案1】:

角度变化检测仅检查对象身份,而不检查对象内容。因此不会检测到插入或删除。

请在此处阅读: https://stackoverflow.com/a/43223700/5835354https://stackoverflow.com/a/42962723/5835354

【讨论】:

  • 这么小的评论,但非常重要 - 我意识到如果我想触发更改检测,我需要重新分配对象。
【解决方案2】:

您的 UI 未更新的原因是 OnPush 更改检测。 OnPush 更改检测仅在数组指针更改但不检查数组内容时触发更改检测(因此呈现)。因此,如果您将一项添加到数组中,它不会改变数组的点。

要解决这个问题,有几种解决方案

  • 移除 OnPush
  • 创建一个新数组
  • 对数组使用 observable

【讨论】:

  • 好吧,我刚刚从另一个帖子添加了 onPush,因为我认为这可以解决我的问题。但它没有。但是由于您所说的,创建一个新数组会有所帮助。谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-03-11
  • 2018-01-20
  • 2018-02-16
  • 2018-06-30
  • 2020-07-27
  • 2010-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多