首页 > 解决方案 > 更改检测后角度子组件未更新

问题描述

也许我从一开始就有错误的设置,但是我遇到了一个问题,@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

所以SubViewwill 只需要绑定到Parent然后每个ChildComponent 就可以拥有它自己的links

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

他们都没有工作。links总是undefined在里面SubView,即使我可以看到当它在内部Child发生变化时,变化实际上正在下降,ParentSubView只是没有检测到变化

值得注意的是,我将每个Child组件都嵌套<router-outlet>ParentComponent 中。

-App
  <router-outlet>
    +Page1
    +Page2
    -Parent
      +SubView
      <router-outlet>
        +Child1
        +Child2
        +...
      +OtherSubView

StackBlitz 示例

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

标签: angular

解决方案


所以,我认为问题在于您没有roleLinks在父组件中分配属性,而是在子组件中(从不使用它)。

如果您有以下 parentComponent 模板

<childComponent [links]="roleLinks></childComponent>

然后roleLinks会从父组件分配给子组件。roleLinks基于类的继承与在原始父项上分配属性无关。

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


推荐阅读