gpt4 book ai didi

Angular 6选择默认值不起作用

转载 作者:太空狗 更新时间:2023-10-29 18:28:43 25 4
gpt4 key购买 nike

我有一个带有默认选定禁用值的选择下拉列表,以及从后端加载的地区列表。我的问题是下拉列表从不显示所选值,始终显示空白。

<form [formGroup]="districtForm">
District:
<select formControlName="districtControl" (change)="filterBuildings($event.target.value)" [value]='' class="form-control">
<option value="" disabled selected>Please select district</option>
<option *ngFor="let district of districts" [ngValue]="district">
{{district.districtName}}
</option>
</select>
<div *ngIf="errorMessageDistrict" class="text-danger">District is required
</div>
</form>

这是我的 ts 代码:

import { Component } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { InfoService } from '../../services/info.service';
import { first } from 'rxjs/operators';
import { District } from '../../models/district';
import { FormGroup, FormControl, FormBuilder } from '@angular/forms';

@Component({
selector: 'app-school-switch',
templateUrl: './school-switch.component.html',
styleUrls: ['./school-switch.component.scss']
})
export class SchoolSwitchComponent {
districts: District[] = [];
selectedDistrict: District;
errorMessageDistrict;
firstDistrict: any;
districtForm = new FormGroup({
districtControl: new FormControl()
});

constructor(
public activeModal: NgbActiveModal,
private infoService: InfoService,
private fb: FormBuilder
) {}

ngOnInit() {
this.infoService
.getDistricts()
.pipe(first())
.subscribe(districts => {
this.districts = districts;
});
}

filterBuildings(filterVal: any) {
this.selectedDistrict = this.districtForm.value.districtControl;
//some more code
}

最佳答案

通常我在 ngOnInit 中创建 FormGroup,然后在其中定义默认值,如下所示:

import { FormGroup, FormBuilder, Validators } from '@angular/forms';

constructor(private formBuilder: FormBuilder){
}

ngOnInit(){
this.districtForm = this.formBuilder.group({
districtControl: ['myDefaultValue', Validators.required]
});
}

关于Angular 6选择默认值不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52370006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com