javascript - 如何在 Reactive Forms 中将 Select 中的当前年份设置为默认值?
问题描述
您好,我创建了一个选择,显示当前年份、过去 5 年和未来 3 年。现在我想设置它,以便当前年份始终是默认值。这应该在反应形式中完成......你知道怎么做吗?
我的代码:
// HTML
<form [formGroup]="sendYearsForm">
<select class="upload_slc" id="upload_slc" required title="" formControlName="year"
(change)="sendYear($event)">
<option *ngFor="let years of sendYears" [value]="years">{{years}}</option>
</select>
<div class="select_arrow"></div>
</form>
// TS
sendYearsForm: FormGroup;
currentDate: Date = new Date();
selectedYear: number;
// Year form
this.sendYearsForm = this.fb.group({
year: [null]
});
// Show the current year with -5 and +3
this.selectedYear = this.currentDate.getFullYear(); // HThe current year is transferred here. How do I integrate it into the template?
for (let i = this.currentDate.getFullYear() - 5; i <= this.currentDate.getFullYear() + 3; i++) {
this.sendYears.push(i);
}
解决方案
You can use patchValue to change the value of a formcontrol
yourFormGroupName.controls.yourFormControlName.patchValue(value you want to assign)
In your case
this.sendYearsForm = this.fb.group({
year: [null]
});
// Show the current year with -5 and +3
this.selectedYear = this.currentDate.getFullYear(); // The current year is transferred here. How do I integrate it into the template?
this.sendYearsForm.controls.year.patchValue(this.selectedYear); // this will set the value of 'year' control to selectedYear(current year)
for (let i = this.currentDate.getFullYear() - 5; i <= this.currentDate.getFullYear() + 3; i++) {
this.sendYears.push(i);
}
推荐阅读
- django - Django - 我可以在 changelist_view 上添加表单吗?
- rabbitmq - RabbitMQ 死信交换 - 通过“x-death.reason”或“x-first-death-reason”标头路由
- python - 如何在 Django Admin.py 中按顺序显示 OrderItem
- python - AttributeError:“HttpResponseSeeOther”对象没有属性“url”
- c++ - 使用非静态成员函数为 std::unique_ptr 设置自定义删除器
- python - 如何使用 Jupyter Notebook 存储来自 scrapy spider 解析函数的数据
- amazon-web-services - 使用 Jenkins Pipeline 的 Terraform 代码中的 AWS 访问和密钥
- unity3d - Hololens 上的 MRTK 和 Vuforia
- excel - 过滤指定列并检查是否有空白单元格,然后删除整行
- javascript - 单击堆栈屏幕的标题右侧图标以导航到本机反应中的其他屏幕