繁体   English   中英

如何获得<input type="date"> TypeScript 中的值

[英]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检查所选元素是否实际上是输入元素:

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 游乐场编译的 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM