首页 > 解决方案 > 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">

标签: angulartypescriptangular8

解决方案


您需要在事件上向父级发出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();
    }
}

推荐阅读