我正在制作一个调查网站,我想做的是从用户那里得到两个日期:开始日期和结束日期,并在这些天之间提供调查(我将在结束日期后禁用调查按钮)。在对这个逻辑进行编码之前,我无法获取用户的输入并将其显示在控制台日志中。以下是目前为止的内容:
HTML:
<input formControlName="startDate" id="startDate" type="date"/>
打印稿:
const startDate = document.getElementById('startDate') as HTMLInputElement | null;
console.log(startDate?.value);
console.log告诉我它是undefined。对如何解决这个问题有什么想法吗?
document.querySelector('input').addEventListener('change', () => {
const startDate = document.getElementById('startDate')
console.log(startDate.value);
})
<input formControlName="startDate" id="startDate" type="date" />
在将回调函数绑定到其change
事件之前,您可以使用类型保护函数来检查所选元素是否实际上是输入元素:
TS操场
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 playground编译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" />
我真的不知道你为什么要在Angular中使用香草Javascript使用Typescript,是不理想的,不是Angular
的方式。
给定您的代码示例,您正在使用ReactiveForms
,您的输入元素有一个formControlName
,这意味着,在组件的逻辑的某个地方,您有整个表单创建为Javascript对象,类似于以下内容:
...
myForm!: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.myForm = this.fb.group({
startDate: ['', Validators.required]
});
}
如果您只想要startDate
控件的值,那么使用访问特定控件的表单对象,如下所示:
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
,你想选择这个输入元素,你可以使用输入元素的本地引用,然后在你的代码中使用ViewChild
访问它,如下所示:
<input type="text" #myName/>
...
@ViewChild('myName') myName!: ElementRef;
getName(): string {
return this.myName.nativeElement.value;
}
如果你不知道如何解决Angular项目中的特定场景,我强烈建议你阅读官方文档。