Home > Back-end >  Angular how to tell if @Input() changes come from parent component
Angular how to tell if @Input() changes come from parent component

Time:09-29

I'm programming in Angular 13 framework and have a ChildComponet which has a few @Input()'s. I'm trying to determine when the value of my inputs are modified from the parent component.

I have a "latLonPickerComponent" which has @Input()'s "latitude" and "longitude". These values will be "undefined" to start but may change to a valid number later on (once an http request finishes running in the parent). I'd like to know (in the child component) when these new values come in from the parent.

I've looked into ngOnChanges as well as @Input-setter-getter but these methods all seem to ALSO change when the values of latitude and longitude are changed WITHIN the child component (unless I'm doing something wrong)

CodePudding user response:

By default, you will always be notified if the reference of the input value changes. I believe, what you are asking is if any property of the object changes (but not the object itself).

Have you seen this post: How to detect when an @Input() value changes in Angular?

CodePudding user response:

Really you can use a setter in the input

Your child:

  <button (click)="name='other one'">change</button>

  name:string=null
  @Input('name') set _name(value: string)
  {
    console.log("Change parent")
    this.name=value;
  };

When change from parent you see the console "Change parent", if you click the button you not.

See a stackblitz

  • Related