[英]How to get <input type=date> value in TypeScript
我正在制作一個調查網站,我想做的是從用戶那里獲取兩個日期:開始日期和結束日期,並在這幾天之間提供調查(我將在結束日期后禁用接受調查按鈕). 在開始編寫此邏輯之前,我無法接受用戶的輸入並將其顯示在控制台日志中。 這是我到目前為止所擁有的:
HTML:
<input formControlName="startDate" id="startDate" type="date"/>
TypeScript:
const startDate = document.getElementById('startDate') as HTMLInputElement | null;
console.log(startDate?.value);
console.log 告訴我它是未定義的。 有想法該怎么解決這個嗎?
document.querySelector('input').addEventListener('change', () => { const startDate = document.getElementById('startDate') console.log(startDate.value); })
<input formControlName="startDate" id="startDate" type="date" />
在將回調 function 綁定到其change
事件之前,您可以使用類型保護 function檢查所選元素是否實際上是輸入元素:
function isInputElement (
value: Element | null | undefined,
): value is HTMLInputElement {
return value?.tagName === 'INPUT';
}
const startDateInput = document.getElementById('startDate');
if (isInputElement(startDateInput)) {
// If the condition evaluates to true,
// then the compiler is certain that it's an <input>:
startDateInput.addEventListener('change', () => {
console.log(startDateInput.value);
//^? (property) HTMLInputElement.value: string
});
}
else {
// The element either didn't exist
// or it wasn't an <input>
}
從 TS 游樂場編譯的 JS:
"use strict"; function isInputElement(value) { return value?.tagName === 'INPUT'; } const startDateInput = document.getElementById('startDate'); if (isInputElement(startDateInput)) { startDateInput.addEventListener('change', () => { console.log(startDateInput.value); }); } else { }
<input formControlName="startDate" id="startDate" type="date" />
我真的不知道你為什么要在使用 Typescript 的Angular項目中嘗試使用香草Javascript ,這並不理想,不是Angular
方式。
鑒於您的代碼示例,您正在使用ReactiveForms
,您的輸入元素有一個formControlName
這意味着,在組件邏輯的某處,您將整個表單創建為 Javascript object,如下所示:
...
myForm!: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.myForm = this.fb.group({
startDate: ['', Validators.required]
});
}
如果您只是想要startDate
控件的值,則使用表單 object 訪問特定控件,如下所示:
getDate(): Date | undefined {
return this.myForm.get('startDate')?.value; // it can be undefined
}
如果您想在每次用戶更改值時監聽輸入更改,請使用如下所示的valueChanges
:
ngOnInit(): void {
this.myForm.get('startDate').valueChanges.subscribe((theDate) => console.log(theDate));
}
假設您沒有使用ReactiveForms
,並且您想要 select 這個輸入元素,您可以使用對輸入元素的本地引用來實現它,然后使用ViewChild
在您的代碼中訪問它,如下所示:
<input type="text" #myName/>
...
@ViewChild('myName') myName!: ElementRef;
getName(): string {
return this.myName.nativeElement.value;
}
如果您不知道如何解決 Angular 項目中的特定場景,我強烈建議您閱讀官方文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.