【问题标题】:Component property becomes null after adding formControlName attribute添加 formControlName 属性后组件属性变为空
【发布时间】: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


【解决方案1】:

因为您使用的是ReactiveForms,通过在字段上设置formControlName,它将允许在控件中设置值,并且您将能够通过console.log(this.dataForm.value) 在您的@987654325 中获取表单值@。

请注意:为 formControl sellerName: [], 传递一个空数组会导致 ERROR 错误:无法读取 null 的属性“名称”...您需要传递一些东西,在 sellerName: [''], 中传递 '' 可以解决错误。

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

堆栈闪电战

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

【讨论】:

    猜你喜欢
    • 2021-12-17
    • 2016-05-04
    • 2022-11-03
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 2021-08-20
    相关资源
    最近更新 更多