单击 Angular 组件外部后无法删除活动框阴影

Unable to remove active box shadow after clicking outside of Angular component

我正在开发这个博客,其中有一个页面列出了所有 post。所以我为每个 post 添加了自定义悬停和活动样式,因此当悬停时它会根据每个 post post.[=14= 显示不同的颜色和框阴影强度]

假设 Post1 有一个与之关联的红色,那么它的默认框阴影颜色将为红色,其模糊度将为 10 像素。但是当鼠标悬停或单击时,它的框阴影也将是红色的,但模糊将是 30px 以聚焦它正在 hovered/clicked.

现在 Post2 如果关联的颜色是蓝色,那么它将有默认值,hover/active box-shadow 颜色为蓝色,blur 分别为 10px 和 30px。

当在 post 外部或另一个 post 上单击时,当前 post 上的活动框阴影将恢复为默认值 (10px)。而这正是我现在无法实现的。当前 post 上的活动阴影不会消失。

这是组件:

@Component({
  selector: 'post',
  templateUrl: './post.component.html', 
  styleUrls: ['./post.component.scss']
})
class Post {
  hoverPostId: number;
  clickedPostId: number;

  constructor() {}

  defaultStyle( color ) {
    const boxShadow = `1px 10px 1px ${color}`;    

    return {
      'box-shadow': boxShadow
    };
  }

  hoverActiveStyle( color ) {
    const boxShadow = `1px 30px 1px ${color}`;    

    return {
      'box-shadow': boxShadow
    };
  }

  postActive( postId: number ) {

    if ( this.post.id === postId ) {
      this.clickedPostId = postId;
    } else {
      this.clickedPostId = null;
    }

  }

  mouseEnter( postId: number ) {
    this.hoverPostId = postId;
  }

  mouseLeave() {
    this.hoverPostId = null;
  }

}

export default Post;

这是模板:

<div 
  class="post" 
  [ngStyle]="hoverPostId === post.id || clickedPostId === post.id ? hoverActiveStyle(post.color) : defaultStyle(post.color)"
  (mouseenter)="mouseEnter(post.id)"
  (mouseleave)="mouseLeave()"
  (click)="postActive(post.id)"
>

   // post content
  
</div>

请注意,我无法在 scss 文件中对悬停和活动 class 的样式进行硬编码,因为每个 post 的颜色都是唯一的。所以请不要这样建议。

=======更新========

还值得一提的是,在我的 Post 组件中,我可以访问所选的 post。像 this.posts.selected 之类的东西 returns 只有一个 post 的数组已被选中。如果未选中,它 returns 为空。

尝试将 tabindex 属性添加到 div

<div 
  tabindex="0"
  class="post" 
  [ngStyle]="hoverPostId === post.id || clickedPostId === post.id ? hoverActiveStyle(post.color) : defaultStyle(post.color)"
  (mouseenter)="mouseEnter(post.id)"
  (mouseleave)="mouseLeave()"
  (click)="postActive(post.id)"
  (blur)="onBlur()"
>

   // post content
  
</div>

如果你在 *ngFor 中有这个,你可以使用迭代的索引

  [tabindex]="i"

元素失去焦点时触发 (blur) 事件。使用 tabindex 设置焦点。

  onBlur() {
    this.clickedPostId = null;
    // Or do your thing here
  }