我们需要在mat-form-field上添加一个事件监听器,以捕捉click事件并阻止其冒泡。以下是一个示例代码:
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { MatFormField } from '@angular/material/form-field';
@Component({
selector: 'app-example',
template: `
`,
})
export class ExampleComponent implements AfterViewInit {
@ViewChild('formField') formField: MatFormField;
constructor(private el: ElementRef) {}
ngAfterViewInit() {
this.formField._elementRef.nativeElement.onclick = (event: MouseEvent) => {
event.stopPropagation();
};
}
handleClick(event: MouseEvent) {
event.stopPropagation();
console.log('click event handled');
}
}
在上面的例子中,我们首先获取mat-form-field的引用,然后在ngAfterViewInit()生命周期钩子中将一个click事件监听器添加到mat-form-field上。在该监听器中,我们调用stopPropagation()以阻止事件冒泡。我们还添加了另一个处理click事件的函数,以确保该事件被正确处理。