【问题标题】:How do I set the current year in my Select as default in Reactive Forms?如何在 Reactive Forms 中将 Select 中的当前年份设置为默认值?
【发布时间】:2020-04-25 14:26:25
【问题描述】:

您好,我创建了一个选择,显示当前年份、过去 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);
    }


【问题讨论】:

    标签: javascript angular typescript angular-material dropdown


    【解决方案1】:

    您可以使用 patchValue 来更改表单控件的值

    yourFormGroupName.controls.yourFormControlName.patchValue(您要分配的值)

    你的情况

    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);
    }
    

    【讨论】:

    • 谢谢。完美答案:)
    【解决方案2】:

    您可以通过以下方式之一进行操作:

    this.selectedYear = this.currentDate.getFullYear();
    this.sendYearsForm= this.fb.group({
      year: new FormControl(this.selectedYear, [])
    });
    

    this.sendYearsForm = this.fb.group({
     year: [null]
    });
    this.selectedYear = this.currentDate.getFullYear();
    this.sendYearsForm.get('year').setValue(this.selectedYear);
    

    【讨论】:

      猜你喜欢
      • 2019-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多