如何根据图标上的点击事件关闭和打开切换按钮

How to Switch off and ON the toggle Button based on the click event on icon

在我的 angular 应用程序中,我有一些字体图标,还有一个拨动开关,默认情况下拨动开关处于打开状态。

我的要求是当我点击任何一个图标时(图标的颜色应该从白色变成红色,这就完成了)。切换开关应该变成关闭状态,当我们点击切换切换彩色图标应从红色变为白色。

.component.html

<label class="rating-switch" id="toggleSwitch">
      <input class="rating-checkbox" type="checkbox" checked >
      <div class="slide round"  >

      </div>
    </label>    <span class="no-rating-switch" >No Rating</span>

<div class="container">
<span class="iconss"></span><i (click)="selectedIcon = icon.id" class="stl" [ngClass]="icon.class"
  [style.color]="selectedIcon === icon.id ? '#FF0000' : '#ffffff'" *ngFor="let icon of icons"></i>
</div>

.component.css

icons = [
    { id: 1, class: "icon-1" },
    { id: 2, class: "icon-2" },
    { id: 3, class: "icon-3" },
    { id: 4, class: "icon-4" },
    { id: 5, class: "icon-5" },
    { id: 6, class: "icon-6" },
    { id: 7, class: "icon-7" },
   
];

所以如上所述,当我点击图标时我必须关闭切换按钮(意味着未选中),当我点击开关时彩色图标应该变为白色。

我尝试了多种方法,谁能帮我解决这个问题。

我认为用一个开关切换多个图标是个坏主意(并且能够通过单击手动切换它们),这让我很困惑。不过没关系,给你。

首先你需要声明每个图标的状态,这样你就知道哪个是active/inactive(如果这背后有任何逻辑,你想知道)。

每次点击一个状态变为活动的图标,它就会变成红色。当您单击切换开关时,其状态变为非活动状态,您的所有图标都将变回白色。

component.html:

 <label class="rating-switch" id="toggleSwitch">
    <input class="rating-checkbox" type="checkbox" [checked]="toggleState" (change)="onToggleClicked($event)">
    <div class="slide round">

    </div>
  </label> <span class="no-rating-switch">No Rating</span>

  <div class="container">
    <span class="iconss"></span>
    <i (click)="onIconClick(icon)" class="stl" [class]="icon- + i"
       [style.color]="icon.active === true ? '#FF0000' : '#ffffff'" *ngFor="let icon of icons; let i = index">
    </i>
  </div>

component.ts:

  toggleState = true;
  icons = [
    {id: 1, class: 'icon-1', active: false},
    {id: 2, class: 'icon-2', active: false},
    {id: 3, class: 'icon-3', active: false},
    {id: 4, class: 'icon-4', active: false},
    {id: 5, class: 'icon-5', active: false},
    {id: 6, class: 'icon-6', active: false},
    {id: 7, class: 'icon-7', active: false},
  ];

  ngOnInit() {
    
  }

  onIconClick(icon: any) {
    let iconToEdit = this.icons.find(ico => ico.id === icon.id);
    if (iconToEdit && !iconToEdit.active) {
      this.icons.forEach(i => i.active = false);
      iconToEdit.active = !iconToEdit.active;
      this.markToggleAsActive();
    } else {
      this.icons.forEach(i => i.active = false);
    }
  }

  onToggleClicked(event: any) {
    this.toggleState = event.target.checked;
    this.markIconsAsInactive();
  }

  markIconsAsInactive() {
    if (!this.toggleState) {
      this.icons.forEach(icon => icon.active = false);
    }
  }

  markToggleAsActive() {
    this.toggleState = !!this.icons.find(icon => icon.active);
  }