繁体   English   中英

检测孩子内部的 Input() 值变化(角度)

[英]Detect Input() Value Change Inside Child (Angular)

我只需要在输入值更改时更新子组件,子组件有一些输入参数,这些参数在 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上使用 setter:

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

此外,您可以使用ngOnChanges

改为挂钩ngOnChanges

示例用法

  @Input() employee: Employee

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM