angular - Angular 8:当用户点击子组件文本框时让父组件检测
问题描述
我有一个带有 Formbuilder 和 ZipCode 文本框的父组件和一个子组件。
我该如何做到这一点,当用户点击子组件文本框时,父组件会知道?用户点击文本框后需要运行业务逻辑。当前文本框基于 Material Angular 包装器。
子组件具有 Formbuilder 和许多文本框,示例如下
this.editAddressForm = this.formBuilder.group({
'city': [null,[Validators.maxLength(50)]],
'zipCode': [null,[Validators.maxLength(10)]],
<app-input-textbox class = "zipcodeclass" div="zipcode" formControlName = "zipCode">
解决方案
您需要在事件上向父级发出blur
事件。
在 HTML 模板中,添加, 并在每个(比如说,和)上添加(blur)="onBlur()"
一个模板引用input
#templateReference1
#templateReference2
#templateReference3
然后在子元素中:
@Output() noInputFocused: = new EventEmitter();
@ViewChild('templateReference1') templateReference1: ElementRef;
@ViewChild('templateReference2') templateReference2: ElementRef;
@ViewChild('templateReference3') templateReference3: ElementRef;
inputs;
constructor(@Inject(DOCUMENT) private document: Document) {}
ngOnInit() {
this.inputs = [templateReference1, templateReference2, templateReference3];
}
onBlur() {
if(this.inputs.map(x => x.nativeElement).indexOf(this.document.activeElement) < 0) {
this.noInputFocused.next();
}
}
推荐阅读
- javascript - 为什么不推荐使用 readAsBinaryString()
- json - 尝试将 json 解析为类对象失败
- php - 根据 WooCommerce 结帐字段值显示/隐藏运输方式
- typescript - 如何使打字稿同步执行?
- swift - 从 Firebase 数据库 IOS 检索信息时出现问题
- r - 将数据框的每一行转换为 R 中的新列表
- spring-mvc - 将 UNICODE 字符转换为通过 Spring MVC @ResponseBody 返回的 JSON 字符串中的 HTML 实体
- hashmap - 拆分地图
进入列表 - r - 从两个数据框制作一个列表并将该列表放在一列中
- wordpress - 将自定义注册块导入古腾堡中的另一个自定义块