Angular 13中ngx-intl-tel-input选国家后下拉框无法关闭问题
解决Angular 13中ngx-intl-tel-input弹窗内下拉框无法自动关闭的问题
问题根源
你给表单内的普通输入框都添加了$event.stopPropagation()来阻止事件冒泡,避免触发弹窗的点击关闭逻辑,但该处理未覆盖ngx-intl-tel-input组件内部的下拉选项点击事件,导致组件无法感知选项点击动作,进而无法自动关闭下拉框。
解决方案
方案1:阻止组件区域内的事件冒泡
给ngx-intl-tel-input标签添加(click)="$event.stopPropagation()",确保点击组件内部(包括下拉选项)时,事件不会冒泡到弹窗的关闭监听上,同时保留组件自身的下拉关闭逻辑。
修改后的组件代码:
<div class="phoneInput-wrapper"> <ngx-intl-tel-input [cssClass]="'custom'" [enableAutoCountrySelect]="true" [enablePlaceholder]="false" [searchCountryFlag]="true" [searchCountryField]="[ SearchCountryField.Iso2, SearchCountryField.Name ]" formControlName="Phone" [selectFirstCountry]="false" [selectedCountryISO]="country" [maxLength]="15" [phoneValidation]="true" [separateDialCode]="false" [numberFormat]="PhoneNumberFormat.National" name="Phone" (countryChange)="getCountry($event)" (click)="$event.stopPropagation()"> <!-- 添加此行阻止事件冒泡 --> </ngx-intl-tel-input> </div>
方案2:优化弹窗关闭逻辑(推荐)
如果方案1无效,可调整弹窗的关闭逻辑,仅在点击弹窗外部时触发关闭,不再通过阻止内部事件冒泡实现。
在弹窗组件的TS文件中添加如下代码:
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; @Component({ // 组件元数据 }) export class YourModalComponent implements AfterViewInit { @ViewChild('modalContainer') modalContainer: ElementRef; ngAfterViewInit() { document.addEventListener('click', (event) => { if (!this.modalContainer.nativeElement.contains(event.target)) { // 执行你的弹窗关闭逻辑 this.closeModal(); } }); } closeModal() { // 弹窗关闭的具体实现,比如隐藏弹窗、销毁组件等 } }
同时移除所有输入框上的(click)="$event.stopPropagation()"和(focus)="$event.stopPropagation()",让组件内部事件正常冒泡,确保ngx-intl-tel-input的下拉关闭逻辑正常执行。
内容的提问来源于stack exchange,提问作者mediocreCoder
相关产品推荐
相关产品推荐

