Home > Enterprise >  How to build a colour pallete in dropdown in angular?
How to build a colour pallete in dropdown in angular?

Time:09-30

I need to build a color-pallet in a dropdown similar to mentioned in below image. and but do not want to hardcode the hex values in the code as I will not be limiting the colors in the pallet in future. I wanted to use ngx-color-picker, so that I can enable the color picker in the later versions.enter image description here

CodePudding user response:

Do you know you can simply do that ?

<input type="color">

It renders a full color palette for you with little to no code.

CodePudding user response:

Using the link @vicnoob indicate, you can "easy" write a component like

<button
  [class.dropup]="upDropdown"
  (click)="isOpen = !isOpen"
  type="button"
  cdkOverlayOrigin
  #trigger="cdkOverlayOrigin"
>
  <div [style.background-color]="value"></div>
  {{ label }}
</button>

<ng-template
  cdkConnectedOverlay
  [cdkConnectedOverlayOrigin]="trigger"
  [cdkConnectedOverlayOpen]="isOpen"
  [cdkConnectedOverlayPositions]="positions"
  [cdkConnectedOverlayWidth]="220"
  (positionChange)="positionChange($event)"
>
  <div >
    <button
      *ngFor="let color of colores"
      (click)="value = color; isOpen = false"
      [style.background-color]="color"
      [style.border]="color=='#ffffff'?'1px solid silver':null"
    ></button>
  </div>
</ng-template>

Where you define some @Input

  @Input() label = 'Choose color';
  @Input()colores = ['#e91c2b','#f48a1d','#eacf2a','#0aa350',
                     '#44a0e3','#cc0098','#663398','#6e340e',
                     '#101113','#cccccc','#ffffff']

For the positions we need define a serie of predefined ConnectedPosition, some like

export const POS: {
  top: ConnectedPosition;
  right: ConnectedPosition;
  bottom: ConnectedPosition;
  left: ConnectedPosition;
} = {
  top: {
    originX: 'start',
    originY: 'top',
    overlayX: 'start',
    overlayY: 'bottom',
    offsetY: -5,
    offsetX: 0,
    panelClass: '',
    weight: 120,
  },
  ...
}

In this way, we can define another input

  @Input('positions') set _positions(value:string[])
  {
    this.positions=value.map(x=>POS[x]|| null).filter(x=>x)
  }

The last detail is control the position of the cdkdrop to change the class of the "caret". For this we need use ngZone

  positionChange(event) {
    this._ngZone.run(() => {
      this.upDropdown = event.connectionPair.overlayY == 'bottom' ? true : null;
    });
  }

Well, implement controlValueAccesor to make a Custom Form Component

And "voilá". This is the final stackblitz

  • Related