如何使用字符串(十六进制格式)初始化 @angular-material-components/color-picker side .ts

hhé*_*zre 1 color-picker angular angular10

我尝试\n将十六进制字符串转换为颜色(导入@角材料组件/颜色选择器)\n也不实例化颜色并在我的数据库中设置我的值十六进制库存\n从侧面.ts

\n

\r\n
\r\n
<!-- begin snippet: js hide: false console: true babel: false -->
Run Code Online (Sandbox Code Playgroud)\r\n
mat-form-field>\n                              <input matInput [ngxMatColorPicker]="picker" formControlName="color" [style.background-color]="getfCAll(ri)"  [disabled]="disabled">\n                              <ngx-mat-color-toggle matSuffix [for]="picker"></ngx-mat-color-toggle>\n                              <ngx-mat-color-picker #picker [touchUi]="touchUi" [color]="color"></ngx-mat-color-picker>\n                            </mat-form-field>
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n

createPriority(p): FormGroup {\n    return this.formBuilder.group({\n      name: [p.name, Validators.compose([Validators.required])],\n      color: [p.color, Validators.compose([Validators.required])]\n    });\n  }\n
Run Code Online (Sandbox Code Playgroud)\n\n

\r\n
\r\n
createPriority(p): FormGroup {\n    return this.formBuilder.group({\n      name: [p.name, Validators.compose([Validators.required])],\n      color: [p.color, Validators.compose([Validators.required])]\n    });\n  }\n
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n\n我弹出白色窗口\n在此处输入图像描述

\n

小智 5

首先,您需要将颜色转换为 RGB,可以使用以下方法:

hexToRgb(hex) {
  const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  hex = hex.replace(shorthandRegex, (m, r, g, b) => {
    return r + r + g + g + b + b;
  });
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}    
Run Code Online (Sandbox Code Playgroud)

那么你需要获取 NgxMatColorPickerInput 的实例

import { NgxMatColorPickerInput, Color } from '@angular-material-components/color-picker';
Run Code Online (Sandbox Code Playgroud)

...

@ViewChild(NgxMatColorPickerInput) pickerInput: NgxMatColorPickerInput;
Run Code Online (Sandbox Code Playgroud)

现在你可以像这样轻松设置值

ngAfterViewInit(): void {
  const temp = this.hexToRgb('#00ff00');
  this.pickerInput.value = new Color(temp.r, temp.g, temp.b);
}
Run Code Online (Sandbox Code Playgroud)