添加formControlName属性后,组件属性变为null

时间:2018-12-11 10:16:13

标签: angular

我正在尝试以反应形式设置组件的验证。在我向组件添加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属性后会发生此错误?如何将列表项的值添加到表单生成器中以进行验证?

1 个答案:

答案 0 :(得分:0)

由于您使用的是ReactiveForms,因此通过在字段上设置formControlName,可以在控件中设置值,并且可以通过{{1 }}中的console.log(this.dataForm.value)

  

请注意::为formControl onSubmit()传递空数组将导致错误   错误:无法读取null的属性“名称” ...您需要传递一些信息,在sellerName: [],中传递''可解决该错误。

请参阅下面的stackblitz。填写表单并提交后,您的值会正确登录到控制台。

Stackblitz

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