在 Angular 中处理事件主要涉及模板事件绑定、事件对象操作、自定义事件以及事件传播控制。以下是详细指南:
html<!-- 模板中直接绑定 --><button (click)="handleClick($event)">点击</button> <!-- 内联表达式 --><input (input)="username = $event.target.value">typescripthandleClick(event: MouseEvent) { // 类型断言确保类型安全 const target = event.target as HTMLButtonElement; // 阻止默认行为 event.preventDefault(); // 停止事件传播 event.stopPropagation(); // 获取坐标 console.log(event.clientX, event.clientY);}html<input (keydown.enter)="onEnterKey()"><input (keydown.control.z)="handleUndo()">typescript@Output() itemSelected = new EventEmitter<string>(); selectItem(item: string) { this.itemSelected.emit(item);}父组件:
html<child-component (itemSelected)="handleItemSelect($event)"></child-component>typescript// 阻止事件冒泡@HostListener('click', ['$event'])onClick(event: MouseEvent) { event.stopPropagation();} // 捕获阶段处理@HostListener('click', ['$event'], true) // 第三个参数表示捕获阶段onCaptureClick(event: MouseEvent) { console.log('Capture phase');}typescriptimport { fromEvent } from 'rxjs'; ngAfterViewInit() { fromEvent(this.myButton.nativeElement, 'click') .pipe( throttleTime(1000), filter(e => e.ctrlKey) ) .subscribe(event => this.handleCtrlClick());}trackBy 优化列表渲染:typescripttrackByFn(index: number, item: any): number { return item.id; // 唯一标识符}typescript// 推荐<button (click)="handleClick()"> // 避免(每次变更检测都会创建新函数)<button (click)="handleClick(item.id)">*ngIf 移除内存泄漏?
typescriptprivate subscriptions = new Subscription(); ngOnInit() { this.subscriptions.add( fromEvent(window, 'resize').subscribe(...) );} ngOnDestroy() { this.subscriptions.unsubscribe();}最佳实践建议:
addEventListener@Output + EventEmitter 模式ChangeDetectionStrategy.OnPush 优化事件频繁触发的组件typescriptimport { debounceTime } from 'rxjs/operators'; fromEvent(window, 'resize').pipe( debounceTime(300)).subscribe(...);根据具体场景选择合适的事件处理方式,需要更多细节可以告诉我具体的使用场景哦!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。