【发布时间】:2019-05-12 07:28:43
【问题描述】:
我正在尝试以反应形式为组件设置验证。该组件工作正常,直到我将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: []
});
Stackblitz: https://stackblitz.com/edit/angular-rahzjd
为什么在我添加 formControlName 属性后会出现此错误,如何将列表项的值获取到表单构建器中进行验证?
【问题讨论】:
-
你能创建stackblitz吗
-
@coder,试着让错误告诉你:添加属性“name”
name="name" formControlName="sellerName" [dropdownItems] ="卖家" > -
我会把它贴在 stackblitz 上
-
使用安全导航操作符
{{selectedItem?.name}} {{selectedItem?.unit}}应该适合你 -
@yurzui 现在可以使用了,当它们在 myForm 中更改时,我如何获取 selectedItem 值
标签: angular