[英]How to use [(ngModel)] on <input type="color"> in a material dialog?
我的問題:
當我嘗試在材質對話框中的顏色輸入元素上使用 ngModel 時,我在 chrome 中收到以下警告消息:
The specified value "" does not conform to the required format. The format is "#rrggbb" where rr, gg, bb are two-digit hexadecimal numbers.
我做錯了什么? 或者這是來自 Angular6 的錯誤?
我的代碼:
顏色.html
<input type="color" [(ngModel)]="color" />
應用程序組件.html
<button (click)="openDialog()">Open Color Dialog</button>
app.component.ts
import { Component } from '@angular/core';
import { MatDialog, MatDialogRef } from '@angular/material';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(public dialog: MatDialog) { }
openDialog(): void {
const dialogRef = this.dialog.open(ColorDialogComponent);
}
}
@Component({
selector: 'app-color',
templateUrl: 'color.html',
})
export class ColorDialogComponent {
constructor(public dialogRef: MatDialogRef<AppComponent>) { }
onNoClick(): void {
this.dialogRef.close();
}
}
這不是錯誤,實際上是警告。 它應該工作正常,對我有用。
我在這個問題上花了一些時間,我已經得出結論,這是一個錯誤。
無論您如何初始化 ngModel 值,它的行為始終如此。
嘗試使用 FormControl
@Component({
selector: 'app-color-input',
templateUrl: './color-input.component.html',
styleUrls: ['./color-input.component.scss']
})
export class ColorInputComponent implements OnInit {
@ViewChild('colorInputEl') colorInputEl: ElementRef;
colorInput: FormControl = new FormControl('#000000');
constructor() { }
ngOnInit(): void {
this.colorInput.valueChanges.subscribe((value) => {
this.colorChanged(value);
});
}
...
}
<input #colorInputEl [formControl]="colorInput" matInput type="color"
placeholder="Choose Color" />
我添加了元素引用,以防您需要它來觸發點擊或其他東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.