![](/img/trans.png)
[英]Assign the value of a checkbox to a FormControlName (Angular)
[英]How to assign formControlName in Angular?
我對角度形式感到困惑。 我有以下幾行代碼。 我給了 formControlName 和 id 我認為是正確的。 但是有了這個代碼,我得到了
ERROR TypeError: Cannot convert undefined or null to object
我不確定我犯了什么錯誤。 任何人都可以幫助我。 這有點令人沮喪。
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: '',
});
}
<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));
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.