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事件仍然会触发,并且可以正常处理。

相关内容

热门资讯

最新技巧!hhpoker买挂,... 最新技巧!hhpoker买挂,wepoker私人局辅助器怎么用,一直有挂(确实有挂)1、起透看视 w...
推荐十款!wepoker透视脚... 推荐十款!wepoker透视脚本免费使用视频,wepoker黑侠破解,果然真的是有挂(有挂技术)1)...
总算明白!aapoker怎么设... 总算明白!aapoker怎么设置提高好牌几率,德州局透视脚本免费版下载手机版,原来是真的有挂(真实有...
信息共享!wepoker软件辅... 信息共享!wepoker软件辅助程序,aapoker怎么开辅助器,原来是真的有挂(存在有挂)信息共享...
今日公布!德普之星辅助软件,w... 今日公布!德普之星辅助软件,wepoker免费脚本,都是是有挂(有挂助手)1、这是跨平台的wepok...
9分钟了解!aapoker透视... 9分钟了解!aapoker透视插件,aapoker能控制牌吗,其实是真的有挂(有挂功能)1、首先打开...
最新研发!wepoker有没有... 最新研发!wepoker有没有透视方法,impoker辅助,总是真的有挂(有挂规律)1、下载好正确养...
科普常识!wepoker游戏的... 科普常识!wepoker游戏的安装教程,wpk免费辅助,其实是真的有挂(有挂教程)1、每一步都需要思...
每日必看推荐!拱趴大菠萝开挂方... 每日必看推荐!拱趴大菠萝开挂方法,hhpoker有作弊的吗,其实是有挂(有挂秘籍)1、实时透视辅助更...
交流学习经验!hhpoker软... 交流学习经验!hhpoker软件可以玩吗,aapoker透视脚本,真是是真的有挂(有挂实锤)1、玩家...