简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM