RAHUL KUNDU
RAHUL KUNDU

Reputation: 955

How to detect change with same value @Input() in Angular?

I have an Angular Custom scroll directive with an @Input() where I am passing an HTML element as a parameter to move the scrollbar to that specific HTML Element.

With this approach, if I pass the same HTML Element multiple times, the Input detecting changes only for the first time after that it is not detecting any changes.

Is there any way to force Angular to detect change for the same input?

@Input() set elementToScroll(element: HTMLElement) {
    if (element != undefined) {
        console.log(element); // Detecting first time only for same input
        this._osInstance?.scroll(
            { el: element, block: { y: 'begin' } },
            500
        );
    }
}

Upvotes: 2

Views: 5624

Answers (2)

Eliseo
Eliseo

Reputation: 58039

You can also use a "trick", pass to your input an object {element:element}

@Input() set elementToScroll(element:{element:HTMLElement}) {
    //use element.element
    if (element.element != undefined) {
        console.log(element.element); 
        this._osInstance?.scroll(
            { el: element.element, block: { y: 'begin' } },
            500
        );
    }
}

//in your parent you has some like:

@ViewChild('move') myElement:ElementRef
click(){
   this.parameter={element:myElement.nativeElement}
}

Upvotes: 2

Michael Mairegger
Michael Mairegger

Reputation: 7301

Extend your component with the interface OnChanges and implement the ngOnChanges method:

ngOnChanges(changes: SimpleChanges) {
    if(changes['myProperty']) {
        // myProperty has changed
   }
}

If you set the same value twice then depending on the type of value this solution works or will be triggered only once.

  • If the type of myProperty is string, number, ... then it will be triggered only once
  • If the type is complex then the solution works.

See the console output for the following sample: https://stackblitz.com/edit/angular-ivy-rd8szx

Upvotes: -1

Related Questions