我很好奇是否有任何方法可以在控制臺中添加自定義警告,類似于當您嘗試在已系結到 .ts 檔案中的 FormControl 的輸入上使用“禁用”屬性時,Angular 拋出的警告. 基本上,Angular 建議您在 .ts 磁貼中修改 FormControl 本身的“禁用”屬性,而不是在模板中指定 HTML 屬性。
為了確保 FormControl 的“狀態”操作代碼完全在 .ts 檔案中完成,每當有人嘗試在 HTML 模板中使用所述“必需”屬性而不是添加時,我還想在控制臺中拋出類似的警告Validators.required 驗證器直接傳遞給 FormControl。
實施此類警告的好方法是什么?
uj5u.com熱心網友回復:
看看reactive_errors.ts:
static disabledAttrWarning(): void {
console.warn(`
It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true
when you set up this control in your component class, the disabled attribute will actually be set in the DOM for
you. We recommend using this approach to avoid 'changed after checked' errors.
Example:
form = new FormGroup({
first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
last: new FormControl('Drew', Validators.required)
});
`);
}
所以基本上 - 這只是一個寫得很好的console.warn. 為了對required屬性做類似的事情,您可以使用[required]選擇器通過指令檢測元素- 并console.warn在其上添加一個ngAfterViewInit()
uj5u.com熱心網友回復:
正如其他答案中提到的,您可以為此創建一個指令。您可能想要處理具有表單控制元件或表單控制元件名稱的欄位,這里是formControlName:
@Directive({
selector: 'input[formControlName]'
})
export class RequiredDirective {
constructor(private el: ElementRef) {
if (this.el.nativeElement.required) {
console.error("set the required attribute on the formcontrol")
}
}
}
演示:https : //stackblitz.com/edit/angular-gfbvbg? file = src/app% 2Frequired.directive.ts
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/365767.html
標籤:有角的
上一篇:在PDFBox中設定文本顏色
