如何使用HostListener与指令实现<p>标签点击切换CSS类
修改方案
要实现点击<p>标签切换删除线样式的效果,直接修改指令代码即可,CSS和HTML部分保持不变:
保留原CSS
.strikethrough { text-decoration: line-through;}
保留原HTML
<p optionalIngredient>ABCD</p>
修改后的指令代码
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core'; @Directive({ selector: '[optionalIngredient]' }) export class OptionalIngredientDirective { // 新增状态变量,跟踪样式是否激活 private isStrikethroughActive = false; constructor(private elRef: ElementRef, private renderer: Renderer2) { } // 替换为click事件监听 @HostListener('click') onClick() { // 每次点击切换状态 this.isStrikethroughActive = !this.isStrikethroughActive; if (this.isStrikethroughActive) { this.renderer.addClass(this.elRef.nativeElement, 'strikethrough'); } else { this.renderer.removeClass(this.elRef.nativeElement, 'strikethrough'); } } }
关键改动说明
- 新增
isStrikethroughActive布尔变量,用来记录当前元素是否已经应用了删除线样式 - 将原来的
mouseenter和mouseleave事件监听替换为click事件,只需要一个点击处理方法 - 在点击方法中,先切换状态值,再根据当前状态决定是添加还是移除CSS类
内容的提问来源于stack exchange,提问作者user17449555
相关产品推荐
相关产品推荐

