angular - 如何在 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>
解决方案
试试这个例子
在 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));
}
}
}
推荐阅读
- flutter - 颤振:如何在firestore的现有集合中添加数据
- laravel - Laravel - 如何根据条件更新员工表
- javascript - 解析模块说明符时出错:logrocket,使用 npm 或 yarn
- c# - HttpResponseMessage' 不包含 'GetAwaiter' 的定义,并且没有可访问的扩展方法 'GetAwaiter'
- javascript - 我如何为 innerHTML 设置动画
- javascript - 有没有办法将 JqGrid 中的行选择与行导航同步?
- r - 在 R 中显示所有可能的具有限制的类别组合
- react-native - 通过 switch navigator 传递参数 react native
- python - Django 需要使用特定版本的 Python
- javascript - 如何修改对匿名函数的所有引用