首页 > 解决方案 > How to change color of button text in popover in ionic 4

问题描述

I am trying to change the text color on the button when the user has made the selection from a popover, so that when the user opens the popover again the previous selection is highlighted...It's for a filter list, user selects filter values desc or asc or by name, etc.

in my html file I have 3 buttons:

<ion-button class="btn1" (click)="sortList('Desc', 'secondary')" fill="clear" [color]="(colorSelect==='secondary')"? 'secondary':'tertiary'">Desc</ion-button>
<ion-button class="btn2" (click)="sortList('Desc', 'secondary')" fill="clear" [color]="(colorSelect==='secondary')"? 'secondary':'tertiary'">Desc</ion-button>
<ion-button class="btn3" (click)="sortList('Desc', 'secondary')" fill="clear" [color]="(colorSelect==='secondary')"? 'secondary':'tertiary'">Desc</ion-button>

in my Component file:

colorSelect: string = '';

public sortList(sortType, item: string){
    this.popoverController.dismiss(sortType);
    this.colorSelect = item;
}

How would you keep that item selected after the popover has closed so that when the popover is opened again, the item would be hightlighted?

标签: ionic4

解决方案


由于 popover 使用了一个在 popover 关闭后被销毁的组件,因此您需要利用 popover 组件可以导入并用作按钮颜色的真实来源的服务。

非常粗略: https ://stackblitz.com/edit/ionic-angular-v5-xfe357

在高水平:

服务.ts:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class SharedService {

  public filters;

  constructor() {
    this.filters = ["secondary","secondary","secondary"]
  }

}

popover.ts:

import { Component } from '@angular/core';
import { PopoverController } from '@ionic/angular';
import { SharedService } from './shared.service';

@Component({
  selector: 'hello',
  template: `<h1>Hello!</h1>
  <ion-list>
      <ion-button class="btn1" (click)="sortList(0, 'Desc', 'secondary')" fill="clear" [color]="sharedService.filters[0]">Desc</ion-button>
      <ion-button class="btn2" (click)="sortList(1, 'Desc', 'secondary')" fill="clear" [color]="sharedService.filters[1]">Desc</ion-button>
      <ion-button class="btn3" (click)="sortList(2, 'Desc', 'secondary')" fill="clear" [color]="sharedService.filters[2]">Desc</ion-button>
  </ion-list>
  `
})
export class HelloComponent  {

  constructor(private sharedService: SharedService, private popoverController: PopoverController) {

  }

  sortList(buttonIndex, sortType, item: string){
    if (this.sharedService.filters[buttonIndex]==="secondary") {
      this.sharedService.filters[buttonIndex]="tertiary";
    } else {
      this.sharedService.filters[buttonIndex]="secondary";
    }
    this.popoverController.dismiss(sortType);
  } 
}

因此,您调用 popover 的主要组件也应该导入此类服务(并注入它)并利用其中的数据作为单一事实来源。


推荐阅读