angulartypescriptangular-input

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
        );
    }
}

Solution

  • 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}
    }