我正在尝试以反应形式为组件设置验证。在将formControlName="sellerName"
添加到组件之前,组件运行良好,现在我收到了以下错误:
ERROR TypeError: Cannot read property 'name' of null
表单组件HTML:其中selectedItem
是空对象
<app-dropdown-select formControlName="sellerName" <-- Removing this makes it work
[dropdownItems]="sellers">
</app-dropdown-select>
下拉组件HTML/模板
<div class="button-container">
<div class="dropdown-button"
(click)="onClick($event)"
[class.dropdown-active]="showList && !combinedInput"
[class.dropdown-input-active]="showList && combinedInput">
<div class="downdown-selected-item">
{{selectedItem.name}} {{selectedItem.unit}}
</div>
<span class="spacer"></span>
<i class="material-icons">
{{buttonIcon}}
</i>
</div>
<div class="dropdown-items" *ngIf="showList">
<div *ngFor="let item of dropdownItems" (click)="onClickItem(item)" class="dropdown-item">
{{item.name}},
{{item.description}}
</div>
</div>
</div>
组件:
@Component({
selector: 'app-dropdown-select',
templateUrl: './dropdown-select.component.html',
styleUrls: ['./dropdown-select.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => DropdownSelectComponent),
multi: true
}
]
})
export class DropdownSelectComponent implements ControlValueAccessor {
@Input() combinedInput: boolean;
@Input() dropdownItems: DropdownItem[];
@Output() selectedItem: DropdownItem;
propagateChange = (_: any) => {};
showList: boolean;
buttonIcon: string;
constructor(private el: ElementRef) { }
ngOnInit() {
this.buttonIcon = BUTTON_ICON_INACTIVE;
this.selectedItem = this.dropdownItems[0];
console.log(this.dropdownItems);
}
onClick() {
this.toggleShowList();
}
toggleShowList() {
this.showList = !this.showList;
if (!this.showList) {
this.buttonIcon = BUTTON_ICON_INACTIVE;
} else {
this.buttonIcon = BUTTON_ICON_ACTIVE;
}
}
onClickItem(item) {
this.showList = false;
this.selectedItem = item;
this.propagateChange(this.selectedItem);
}
writeValue(value: any) {
if (value !== undefined) {
this.selectedItem = value;
}
}
registerOnChange(fn) {
console.log('register change');
this.propagateChange = fn;
}
registerOnTouched() {}
}
表单组:
this.myForm = this.fb.group({
name: ['', [Validators.required, Validators.minLength(3)]],
description: ['', [Validators.required, Validators.minLength(10)]],
cost: [],
amount: [], // component
sellerName: [], // component
sellerUrl: []
});
堆栈闪电战:https://stackblitz.com/edit/angular-rahzjd
为什么在添加formControlName属性后会出现此错误,以及如何将列表项的值获取到表单生成器中进行验证?
因为您使用的是ReactiveForms
,通过在字段上设置formControlName
,它将允许在控件中设置值,并且您将能够通过onSubmit()
中的console.log(this.dataForm.value)
获取表单值。
请注意:为formControl
sellerName: [],
传递空数组会导致错误错误:无法读取null的属性"name">。。。您需要传递一些东西,在sellerName: [''],
中传递''
可以解决错误。
请参阅下面的stackblitz。当您填写表格并提交时,您的值会正确地记录在控制台中。
堆叠闪电
https://stackblitz.com/edit/angular-mjqjsc?embed=1&file=src/app/form/form.component.html