4

I have two components Parent Component and Child component, I have an API that takes place in the Parent component and the response value is passed to the child component. currently I am using ngOnChanges but I want to know how to use Setters instead.

assume In the ParentComponent I have the below code:

<ChildComponent [apiResponse]="res" />

and in the ChildComponent I have this:

@Input() apiResponse: any;

ngOnChanges(changes: SimpleChanges) {
    console.log(this.apiResponse)
}

Every time the apiResponse changed the ngOnChanges function will fire and prints the value in the console.

if I want to achieve the result but with the use if Setters. as in other scenario I might have multiple inputs and I don't want ngOnChanges to get fired every time an input's value changed.

1

1 Answer 1

10

Instead of:

@Input() apiResponse: any;

Use:

@Input() 
get apiResponse(): any {return this._apiResponse;}
set apiResponse(value: any) {
  this._apiResponse = value;
  console.log(value);
  // do whatever else you want to do here
}
private _apiResponse: any;

In the code above, the only really necessary part is the setter function. Without that, you cannot pass in the values from the parent components via @Input()'s. The rest is just a matter of what you want. For example, if you want to save the value to use it later, you need the private member (or a BehaviorSubject or anything you think it's good for storing a value):

@Input() 
set apiResponse(value: any) {
  this._apiResponse$.next(value);
  console.log(value);
  // do whatever else you want to do here
}
_apiResponse$: BehaviorSubject<any> = new BehaviorSubject<any>(null);

In the example above, notice that I haven't made the subject a private member. I suppose you want to use it in the template, so, even though it should be private (not part of the component API), I can't do that because the template needs to access it. The underscore is something to indicate that such a public member is not part of the API.

Sign up to request clarification or add additional context in comments.

1 Comment

can you please use BehaviorSubject to save the data?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.