简体   繁体   English

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

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

I just need to update child component when Input value changes , the child component has some input parameters which set some local variables inside ngInit() but the issue is the parent when change the input parameters the child does not update because ngInit() only trigger once it is initialize.我只需要在输入值更改时更新子组件,子组件有一些输入参数,这些参数在 ngInit() 中设置了一些局部变量,但问题是父组件在更改输入参数时子组件不会更新,因为 ngInit() 只触发一旦初始化。

Inside Parent内部父级

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

On some trigger events the parent changes these properties (as input of child)在某些触发事件上,父级会更改这些属性(作为子级的输入)

Parent Ts父母 Ts

method(ds, columns, footer) {

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

This hit only once even after changing input values即使在更改输入值后也仅命中一次

Child ts儿童 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;
}

Please help , if I can use Input properties directly inside html then how come can i make changes to it?请帮助,如果我可以直接在 html 中使用 Input 属性,那么我怎么可以对其进行更改? Help me know how to notify when Input changes?帮我知道如何在输入更改时通知?

Try using setters on the @Input :尝试在@Input上使用 setter:

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

also, you can use ngOnChanges此外,您可以使用ngOnChanges

hook into ngOnChanges instead:改为挂钩ngOnChanges

example usage示例用法

  @Input() employee: Employee

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

There's also a decorator method .还有一个装饰器方法 Though note the TypeScript decorator is experimental.尽管请注意 TypeScript 装饰器是实验性的。

You can achieve the functionality using ngOnChanges .您可以使用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