0

I want to exec a function every time when the @Input is changed. I tried to do it that way:

 ngOnChanges(changes: { [propName: string]: SimpleChange }) {
  if( changes['inputName'] && changes['inputName'].previousValue != changes['inputName'].currentValue ) {
    this.func();
  }
}

but my problem is: my @Input value is'nt necessarily changed (it can be "a" and another once "a") but even if it's not changed I want to exec the function. what can I do?

3
  • maybe you just get rid of this if statement and just fire this.func() in ngOnChanges body? Commented Jul 2, 2020 at 9:02
  • it can be a good idea, but i have some inputs, and I want to exec the function only when the specific input is changed. Commented Jul 2, 2020 at 9:19
  • What is the type of your input? Commented Jul 2, 2020 at 10:40

2 Answers 2

2

You need to call setter method For @Input() changed everytime..

@Input('inputName') set cmpRef (cmp : any){
   // your function call here goes every time @Input() changes, this setter method is called.
      this.func();
 }
Sign up to request clarification or add additional context in comments.

3 Comments

I tried to do that but the set works only in the first time when the input is changed and not every time.
You have to Immutable your object for Input() to work properly, For this you can use destructing or Object.assign()
@Tammar If answer is helpul to you, You can accept it. Thank you.
0

I solved the problem by putting object in the @Input parameter instead of string only. and now it is changed every time I change it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.