[英]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.我有一个带有
@Input()
的 Angular 自定义滚动指令,我在其中传递一个 HTML 元素作为参数,以将滚动条移动到该特定的 HTML 元素。
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.使用这种方法,如果我多次传递相同的 HTML 元素,则 Input 检测仅在第一次发生变化之后才检测到任何变化。
Is there any way to force Angular to detect change for the same input?有没有办法强制 Angular 检测相同输入的变化?
@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:使用接口 OnChanges 扩展您的组件并实现 ngOnChanges 方法:
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.如果您两次设置相同的值,则根据值的类型,此解决方案有效或仅触发一次。
See the console output for the following sample: https://stackblitz.com/edit/angular-ivy-rd8szx请参阅以下示例的控制台输出: https : //stackblitz.com/edit/angular-ivy-rd8szx
You can also use a "trick", pass to your input an object {element:element}
您还可以使用“技巧”,将对象
{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}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.