1

Is there any way to prevent an Angular Input from receiving any more inputs. I want a child input to receive 3 update changes from ngOnChanges, and on 4th or higher, stop receiving inputs, and stop changing values.

I could put an input count flag on child component ngOnChanges, just curious if there is any better mechanism either in the parent or in the child component, to stop receiving inputs?

Current Solution

ngOnChanges() {
    if (inputCount < 3) { 
       this.customerName = ....
       this.product = ....
} 
  • 2
    It feels like you are trying to fix something that should be fixed in a different place. Can you explain why you want a mechanism like this? I can only imagine this will end up being confusing to consumers of the component – Poul Kruijt May 04 '20 at 20:27
  • hi @PoulKruijt I am working with previous person code, would have to rewrite code, I guess my question is how to turn off change detection? –  May 04 '20 at 20:48
  • I think it's better to debounce the amount of times the value gets updated from outside the component. So handle the changes in the parent, not the child – Poul Kruijt May 05 '20 at 06:24

1 Answers1

0

You can do that with a setter/getter:

@Input() 
get myInput() {return this._myInput;}
set myInput(value: any) {
  if(this._myInputCount >= 3) {
    return;
  }
  this._myInput = value;
  this._myInputCount++;
}
private _myInput: any;
private _myInputCount = 0;
julianobrasil
  • 8,954
  • 2
  • 33
  • 55
  • yeah, I mean setter/getter are alternatives to ngOnchages, I am looking for a stop mechanism in change detection, i already have similar solution, thanks anyway –  May 04 '20 at 20:32
  • I'm afraid there isn't a more simple way to do that. I must agree with @poul-kruijt, maybe there's another problem leading you to this situation that should be reviewed. – julianobrasil May 04 '20 at 20:36
  • hi I am working with previous person code, would have to rewrite code, I guess my question is how to turn off change detection? –  May 04 '20 at 20:49
  • Hum... it's not a trivial thing. Currently, there are some guys talking about disabling `NgZones` (which is responsible for firing the change detection), but it would be done for your entire app. [This other question](https://stackoverflow.com/a/44409244/6433166) maybe can give you a clue. – julianobrasil May 04 '20 at 22:43