Angular的ViewChild valueChange处理程序在组件被*ngIf隐藏和重新显示后停止触发。
创始人
2024-10-24 11:01:29
0

在Angular中,当使用ngIf指令隐藏和重新显示组件时,ViewChild的valueChange处理程序可能会停止触发。这是因为ngIf指令会从DOM中移除组件,并且重新显示时会重新创建组件。为了解决这个问题,可以使用ngAfterViewInit生命周期钩子来重新订阅valueChange事件。以下是一个示例:

在组件中定义ViewChild和订阅valueChange事件的代码:

import { Component, ViewChild, ElementRef, AfterViewInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-my-component',
  template: `
    
` }) export class MyComponent implements AfterViewInit, OnDestroy { @ViewChild('myInput', { static: false }) myInput: ElementRef; private valueChangeSubscription: Subscription; public showComponent: boolean = true; ngAfterViewInit() { this.valueChangeSubscription = this.myInput.nativeElement.valueChanges.subscribe(() => { this.onValueChange(); }); } ngOnDestroy() { this.valueChangeSubscription.unsubscribe(); } onInputChange() { // Do something when input value changes } onValueChange() { // Do something when valueChange event is triggered } toggleComponent() { this.showComponent = !this.showComponent; } }

在上述示例中,我们使用了ViewChild装饰器来获取对输入元素的引用。然后,在ngAfterViewInit生命周期钩子中,我们订阅了valueChange事件,并在回调函数中调用了onValueChange方法。

另外,我们还实现了OnDestroy生命周期钩子,在组件销毁时取消了valueChange事件的订阅,以避免内存泄漏。

最后,在模板中使用了*ngIf指令来根据showComponent属性的值来显示或隐藏组件。通过调用toggleComponent方法,我们可以切换showComponent属性的值,从而隐藏或重新显示组件。

这样,当组件被隐藏和重新显示时,valueChange事件仍然会触发,并且可以正常处理。

相关内容

热门资讯

透视规律"hhpok... 透视规律"hhpoker辅助软件是真的么"wepoker的辅助器(原来真的是有辅助平台)-哔哩哔哩;...
透视神器"fishp... 透视神器"fishpoker透视底牌"wepoker有没有机器人(一直真的是有辅助app)-哔哩哔哩...
连日来"智星德州插件... 连日来"智星德州插件2024最新版"wepoker有没有机器人(一直真的是有辅助工具)-哔哩哔哩1、...
透视黑科技"fish... 透视黑科技"fishpoker透视底牌"wepoker底牌透视(果然真的有辅助工具)-哔哩哔哩1、f...
无独有偶"wepok... 无独有偶"wepoker辅助器安装包定制"aapoker透视脚本(真是是真的辅助平台)-哔哩哔哩we...
透视软件"wepok... 您好,wepoker如何设置透视这款游戏可以开挂的,确实是有挂的,需要了解加去威信【13670430...
于此同时"aapok... 于此同时"aapoker怎么设置抽水"wpk辅助(一直真的是有辅助工具)-哔哩哔哩aapoker怎么...
透视透视"werpl... 透视透视"werplan脚本"hhpoker哪个俱乐部靠谱(果然真的有辅助插件)-哔哩哔哩运hhpo...
透视好牌"wepok... 透视好牌"wepoker透视有没有"wepoker私人局开挂视频(好像是有辅助平台)-哔哩哔哩1、w...
围绕透视问题"哈糖大... 围绕透视问题"哈糖大菠萝破解器"aapoker辅助器是真的吗(本来真的有辅助下载)-哔哩哔哩进入游戏...