【发布时间】:2021-07-06 19:45:32
【问题描述】:
我的选择元素有问题,当我添加 formControlName 时,-- Select Event Type -- 不再显示(但仍在下拉列表中选中)。如果我删除它,它会显示但当然不会验证。
这家伙在这里有同样的问题,但答案对我不起作用:Adding formControlName makes the default value disappear in my form's dropdown in Angular
<select class="form-control" name="type" id="type" formControlName="type" [appValidatedInputControl]="form.get('type')">
<option [value]="" disabled selected>-- Select Event Type --</option>
<option *ngFor="let type of (eventTypes$ | async)" [value]="type">{{ 'eventType.' + type | translate}}</option>
</select>
TS 文件
export class EventCreationFormComponent implements OnInit {
@Input() form: FormGroup;
//...
表单被注入的父 HTML 组件:
<app-event-creation-form [form]="form"></app-event-creation-form>
父组件TS文件
export class EventCreationComponent implements OnInit, OnDestroy {
form: FormGroup;
//...
constructor(private fb: FormBuilder){
this.initForm();
//...
}
initForm() {
this.form = this.eventCreationService.createForm();
const { type, tags } = this.form.controls;
this.subs.sink = type.valueChanges.subscribe((typeValue) => {
if (typeValue && (tags.untouched || !tags.value || !tags.value.length)) {
tags.patchValue([{ value: typeValue, display: typeValue }]);
}
});
//...
}
EventCreationService:
@Injectable()
export class EventCreationService implements OnDestroy {
constructor(private fb: FormBuilder) {}
createForm(): FormGroup {
return this.attachEventHandlers(this.fb.group(
{
type: [undefined, [Validators.required]],
//...
我错过了什么吗?
【问题讨论】:
-
在这种情况下,在作为该表单控件来源的表单中设置默认值
标签: angular angular-forms