首页 > 解决方案 > 如何在 Angular 中分配 formControlName?

问题描述

我对角度形式感到困惑。我有以下代码行。我给了我认为正确的 formControlName 和 id 相同的值。但是有了这段代码,我得到了

ERROR TypeError: Cannot convert undefined or null to object

我不确定我犯了什么错误。任何人都可以帮助我。这有点令人沮丧。

ts。

import { FormGroup, FormBuilder, NgForm } from '@angular/forms';
export class FilterProductTargetComponent implements OnInit {
    public gsmList: any = [];
    public gsmModel = '';
    public filterProductTargetForm: FormGroup;

    constructor(private _service: TestService, private _fb: FormBuilder) { }

    ngOnInit() {
        this.filterProductTargetForm = this._fb.group({
            gsmList: '',
            rsmList: '',
            asmList: '',
        });
    }

html

<form [formGroup]="filterProductTargetForm" novalidate (ngSubmit)="save(filterProductTargetForm.value)">
                <div class="row">
                    <div class="col-md-10">
                        <select [(ngModel)]="gsmModel" id="gsmList" formControlName="gsmList">
                            <option value="" disabled selected>select a category</option>
                            <option *ngFor="let item of gsmList" [value]="item">{{item}}</option>
                        </select>
                    </div>
                </div>

标签: angularangular5angular-forms

解决方案


试试这个例子

在 HTML 中

<form class="example-container" [formGroup]="dropDownGroup" >
  <mat-form-field >
    <mat-select placeholder="Select numeric value" formControlName="numericControl">
      <mat-option value="1">1</mat-option>
      <mat-option value="2">2</mat-option>
      <mat-option value="3">3</mat-option>
    </mat-select>

  </mat-form-field>
    <mat-error *ngIf="this.dropDownGroup.get('numericControl').invalid">Value required</mat-error>
</form>

在 Ts 文件中

import {Component,OnInit} from '@angular/core';
import {  FormBuilder, NgForm ,FormControl, Validators,FormGroup } from '@angular/forms';



@Component({
  selector: 'select-overview-example',
  templateUrl: 'select-overview-example.html',
  styleUrls: ['select-overview-example.css'],
})



export class SelectOverviewExample implements OnInit {

   dropDownGroup:FormGroup

    constructor() { }

    ngOnInit() {
      this.dropDownGroup = new FormGroup({});
      let Validations = [Validators.required]
        if (!this.dropDownGroup.contains("numericControl")) {
         this.dropDownGroup.addControl("numericControl", new FormControl('', Validations));

            }
    }
}

推荐阅读