1

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?

5
  • can you create stackblitz Commented Dec 11, 2018 at 10:27
  • @coder, try make that the error say you: add property "name" < app-dropdown-select name="name" formControlName="sellerName" [dropdownItems]="sellers" > Commented Dec 11, 2018 at 11:36
  • I'll post it on stackblitz Commented Dec 11, 2018 at 12:00
  • Using safe-navigation operator {{selectedItem?.name}} {{selectedItem?.unit}} should work for you Commented Dec 12, 2018 at 4:48
  • @yurzui it works now, how do I get the selectedItem values when they change in myForm Commented Dec 12, 2018 at 5:05

1 Answer 1

1

Because you are using ReactiveForms, by setting the formControlName on the field it will allow the value to be set in the control, and you will be able to get your form values via console.log(this.dataForm.value) in your onSubmit().

Please Note: Passing an empty array for the formControl sellerName: [], results in ERROR Error: Cannot read property 'name' of null... you need to pass something, passing '' in sellerName: [''], resolves the error.

Please see stackblitz below. When you fill out the form and submit, your values are logged in console properly.

Stackblitz

https://stackblitz.com/edit/angular-mjqjsc?embed=1&file=src/app/form/form.component.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.