更改检测后,角子组件未更新

时间:2019-10-16 17:14:04

标签: angular

也许一开始我的设置有误,但是在父级变量更改后,子级组件@Input装饰器没有更新,我遇到了问题。我的问题是,父母的变量实际上正在从父母继承的另一个孩子的组件中得到更新。

子视图组件

@Component({
  selector: 'sub-view',
  templateUrl: './sub-view.component.html',
  styleUrls: ['./sub-view.component.scss']
})
export class SubViewComponent {
  @Input() links;
  ...
}

父项

@Component({
  selector: 'parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss']
})
export class ParentComponent {
  roleLinks:any;

  constructor() {}
  ...
}

父视图

<sub-view 
    [links]="roleLinks" 
></sub-view>

子组件#1

@Component({
  selector: 'child1',
  templateUrl: './child1.component.html',
  styleUrls: ['./child1.component.scss']
})
export class Child1Component extends ParentComponent {
  constructor() {
    super();
    this.roleLinks = [
      {key:'a',val:'A'},
      {key:'b',val:'B'}
    ];
  }
  ...
}

我有Child1Component extends ParentComponent,因为这样的想法是我将有一个Child2Child3等。每个孩子将与Parent有很多共享的成分

因此,SubView仅需要绑定到Parent,然后每个Child组件都可以拥有自己的links

但是,我无法在links中更新SubView 查看其他SO Q / A,我尝试了以下操作:

  • ChangeDetectionStrategy.OnPush添加到SubView
  • detectChanges()中的ChangeDetectorRef添加到SubView
  • markForCheck()中的ChangeDetectorRef添加到SubView

他们俩都不起作用。 links始终位于undefined内部SubView,即使我看到Child内部对其进行更改时,这些更改实际上将其降低到Parent,但是{{ 1}}只是没有检测到更改

可能值得注意的是,我在SubView组件内的嵌套Child中拥有每个<router-outlet>组件。

Parent

StackBlitz示例

https://stackblitz.com/edit/angular-f2qemh

1 个答案:

答案 0 :(得分:2)

因此,我认为问题在于您不是在父组件中分配 protected override void OnShown(EventArgs e) { base.OnShown(e); this.BtnClick(null, null); } 属性,而是在子组件(从未使用过的子组件)中分配。

如果您具有parentComponent的以下模板

roleLinks

然后<childComponent [links]="roleLinks></childComponent> 从父组件分配到子组件。基于类的继承与在原始父项上分配roleLinks属性无关。

相反,您将需要直接分配此属性,或者,如果需要在父子之间共享状态,请使用所需数据创建一个angular service并将其注入到两者中。