I'm trying to setup validation for a component in a reactive form. The component is working fine until I add formControlName="sellerName" to the component, now I get this error:
ERROR TypeError: Cannot read property 'name' of null
Form Component HTML:
Where the selectedItem is the null object
<app-dropdown-select formControlName="sellerName" <-- Removing this makes it work
[dropdownItems]="sellers">
</app-dropdown-select>
Dropdown Component HTML/template
<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:
@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() {}
}
Form group:
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
Why does this error occur after I add the formControlName attribute and how can I get the value of a list item into the form builder to validate it?
{{selectedItem?.name}} {{selectedItem?.unit}}should work for you