添加“删除"垫选择中的按钮 [英] Adding "delete" button in mat-select

查看:58
本文介绍了添加“删除"垫选择中的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello Stackoverflow社区,

Hello Stackoverflow community,

我试图将鼠标悬停在给定 mat-select 的每个 mat-option 旁边,添加一个删除"按钮.悬停部分工作正常.但是,按照我实现此按钮的方式,选择一个选项后显示的数据将被更改:

I am trying to add a "Delete" button next to each mat-option of a given mat-select when hovering over the option itself. The hover portion works just fine. However, given the way I implemented this button, the data displayed after selecting an option is altered :

来自此:

对此:

以下是所用代码的摘要:

Here is a snippet of the code used :

HTML模板:

<mat-form-field appearance="outline">
  <mat-select>
    <mat-option *ngFor="let year of data" [value]="year">

      <div style="display:flex; justify-content: space-between">
        <span>{{year}}</span>
        <span></span>
        <span class="deleteYear" (click)="openDeleteDialog(year)">
          <i class="material-icons-outlined">clear</i>
        </span>
      </div>

    </mat-option>
  </mat-select>
</mat-form-field>

我相信打字稿组件中没有相关代码可共享.但是,我非常愿意在需要时提供源代码.

I believe there is no relevant code in the typescript component to share. However, I'm more than willing to provide the source code if needed.

2个问题:

  1. 如何消除附加在所需"year"字符串上的"clear"("X"图标的名称)文本?
  2. 现在,当我单击"X"按钮时,这些功能将正常运行.但是,它也会在垫选中选择该选项,方法是单击"X",我也单击该行.有什么办法可以使函数启动但使表单不相信我选择了该行?

感谢大家的支持,

推荐答案

您可以使用 mat-select-tigger 因此,您的.html变得像

You can use mat-select-tigger So, your .html becomes like

<mat-form-field appearance="outline">
  <mat-select [formControl]="value">
    <mat-select-trigger>
      {{value.value}}
       <span class="deleteYear" (click)="delete($event,value.value)">
          <mat-icon>clear</mat-icon>
        </span>
    </mat-select-trigger>
    <mat-option *ngFor="let year of data" [value]="year">

      <div style="display:flex; justify-content: space-between">
        <span>{{year}}</span>
        <span></span>
        <span class="deleteYear" (click)="delete($event,year)">
          <mat-icon>clear</mat-icon>
        </span>
      </div>

    </mat-option>
  </mat-select>
</mat-form-field>

然后您的函数删除(*)

And your function delete (*)

  value=new FormControl()

  delete(event:any,year:any)
  {
    event.preventDefault(); //<--prevent default
    event.stopPropagation();  //stop propagation
    this.data=this.data.filter(x=>x!=year) //<--remove the element from data
    if (this.value.value==year)
        this.value.setValue(null) //<--if the value is the remove data, set null

  }

stackblitz

(*)我使用一个formControl,如果您有一个formGroup,请通过以下方式更改this.value

(*) I use a formControl, if you has a formGroup change this.value by

this.form.get(value)

这篇关于添加“删除"垫选择中的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆