首页 文章

当父数据更改Angular 4时,如何强制子组件重新加载其数据及其视图

提问于
浏览
0

我使用角度4.虽然我使用了Angular JS,但我对它有点新鲜 .

我有一个父组件,它有一个对象数组

people: Person[]; //array of Person model

在父组件中,用户通过其视图修改人员阵列

现在,在父组件视图中有一个子组件(personComponent),它遍历people数组,就像这样

<person *ngFor="let person of people; let i = index" [person]="person">

子组件显示personComponent中每个人的百分比

@Input() person:Person; //person model
percent:number;

ngOnInit(){
    this.percent = this.person.percent;
}

现在在父组件中,当将新人添加到people数组时,每个子组件应该具有新的百分比 .

所以我在父组件中创建了一个计算每个人百分比的方法

setPercent(){
  this.people.forEach((p)=>{
     p.percent = Math.round((p.value/this.total_amount)*100) //total amount is a variable in the parent component
  })
}

现在,每次添加新人时都会调用setPerson方法...问题是子组件不更新其数据,并且不更新people数组中每个人的百分比 .

我已经尝试在子组件person变量上使用ngOnChanges,但是没有更新子组件数据,因此子组件视图也没有更改 . 我该怎么办

2 回答

  • 0

    Person 组件中,您在初始化时获取百分比值,不再更新它 . 您可以使用具有始终最新值的 person 属性,而不是这样做 . 所以你应该可以使用它

    {{person.percentage}}
    

    在你的模板中 .

  • -1

    在您的子组件上使用以下内容:

    import {ChangeDetectionStrategy} from '@angular/core';
    @Component({
      // your selector and template
      changeDetection: ChangeDetectionStrategy.onPush
    })
    

    并在您的父组件中尝试以下操作:

    import {ChangeDetectionRef} from '@angular/core';
    

    并在构造函数中注入它:

    constructor(private cd:ChangeDetectorRef){}
    

    并在您的方法中更新百分比:

    setPercent(){
     this.people.forEach((p)=>{
     p.percent = Math.round((p.value/this.total_amount)*100) //total amount is a 
       variable in the parent component
     });
     //TRY THIS
     this.cd.detectChanges();
     //OR THIS
     this.cd.markForCheck();
    }
    

    此代码将告知更改检测以检查组件及其子组件的更改 .

相关问题