【问题标题】:Detect Input() Value Change Inside Child (Angular)检测子项内部的输入()值​​变化(角度)
【发布时间】:2020-04-11 20:05:23
【问题描述】:

我只需要在输入值更改时更新子组件,子组件有一些输入参数,它们在 ngInit() 中设置了一些局部变量,但问题是父组件在更改输入参数时子组件不会更新,因为 ngInit( ) 仅在初始化后触发。

在父级内部

<app-site-parameter-tbl *ngIf="siteTbl==true" [siteParameterTDataSet]="siteParameterDataSet" [siteParameterTGridColumns]="siteParameterColumns" [siteParameterFoot]="siteParameterFooter" [siteParameterT]="siteParameterTbl" [model]="siteModel" [bckColor]="this.tabBackColor"></app-site-parameter-tbl>

在某些触发事件上,父级会更改这些属性(作为子级的输入)

父 Ts

method(ds, columns, footer) {

    this.siteParameterDataSet = ds;
    this.siteParameterColumns = columns;
    this.siteParameterFooter = footer;
}

即使在更改输入值后也只命中一次

儿童 ts

@Input() siteParameterT: boolean;
@Input() model: SiteModel;
@Input() siteParameterFoot: [];
@Input() siteParameterTGridColumns: [];
@Input() siteParameterTDataSet: any;

ngOnInit() {
    debugger;
    //setting local variables then they will render inside html

    this.siteParameter = this.siteParameterT;
    this.site = this.model;
    this.foot = this.siteParameterFoot;
    this.dataSet = this.siteParameterTDataSet;
}

请帮忙,如果我可以直接在 html 中使用 Input 属性,那我怎么能对其进行更改? 帮助我了解如何在 Input 更改时进行通知?

【问题讨论】:

标签: angular typescript


【解决方案1】:

尝试在@Input 上使用设置器:

@Input('siteParameterT')
set siteParameterT(value: boolean) {
    this.siteParameter = value
}

另外,你可以使用ngOnChanges

【讨论】:

  • 非常感谢您抽出宝贵的时间,但 ngOnChanges 运行良好。投票..再次感谢
【解决方案2】:

改为挂钩ngOnChanges:

示例用法

  @Input() employee: Employee

  ngOnChanges(changes: SimpleChanges) {
    /** Fire any time employee changes */
    if (changes.employee && changes.employee.currentValue) {
      this.formGroup.patchValue(this.employee)
    }
  }

还有一个decorator method。尽管请注意 TypeScript 装饰器是实验性的。

【讨论】:

    【解决方案3】:

    您可以使用ngOnChanges 实现该功能。

     public ngOnChanges(changes: SimpleChanges): void {
        this.siteParameter = changes.siteParameter;
        etc.,
      }
    

    【讨论】:

    • 非常感谢您抽出宝贵的时间,但 ngOnChanges 运行良好。投票..再次感谢
    猜你喜欢
    • 2018-12-22
    • 1970-01-01
    • 2023-01-13
    • 2021-01-27
    • 1970-01-01
    • 2021-06-17
    • 2021-08-07
    • 2018-10-24
    • 1970-01-01
    相关资源
    最近更新 更多