Reputation: 329
I have been getting the following error: ERROR Error: Must supply a value for form control with name: 'id'. even though i have provided value for the same and here is my typescript code
import { Component, OnInit,Inject } from '@angular/core';
import {MatDialog,MatDialogRef,MAT_DIALOG_DATA} from '@angular/material';
import {FormGroup,FormBuilder,Validators} from '@angular/forms';
import {AdminService} from '../../services/admin.service';
@Component({
selector: 'app-subcategory-modal',
templateUrl: './subcategory-modal.component.html',
styleUrls: ['./subcategory-modal.component.css']
})
export class SubcategoryModalComponent implements OnInit {
subcategoryForm:FormGroup;
category:any;
constructor(public subCategoryDialogref:MatDialogRef<SubcategoryModalComponent>,@Inject(MAT_DIALOG_DATA)public data:string,private formBuilder:FormBuilder,private service:AdminService)
{
this.generateCategory();
}
ngOnInit() {
this.createForm();
this.generateSubcategory(this.data);
}
createForm()
{
this.subcategoryForm=this.formBuilder.group({
id:[null,Validators.required],
subcategoryName:[null,Validators.required],
category:[null,Validators.required]
});
}
generateSubcategory(data)
{
this.service.getSubcategorys(data).subscribe(res=>{
console.log(res.result);
this.subcategoryForm.setValue({
id:res.result.Name
});
},err=>{
});
}
generateCategory()
{
this.service.getCategory().subscribe(res=>{
this.category=res;
});
}
}
and this is my html code :-
<form [formGroup]="subcategoryForm">
<div class="form-group">
<input type="text" class="form-control" formControlName="id"value="" name="id">
</div>
<div class="form-group">
<input type="text" class="form-control" formControlName="subcategoryName" name="subcategoryName" >
</div>
<div class="form-group">
<select class="form-control" name="category" formControlName="category">
<option value="0">-Select-</option>
<option *ngFor="let data of category?.result" value="{{data.id}}">{{data.Name}}</option>
</select>
</div>
<div class="form-group text-center">
<button type="button" class="btn btn-primary" name="button">Update</button>
</div>
</form>
can anybody tell me where i'm going wrong? and why this error keeps happening?
Upvotes: 2
Views: 4088
Reputation: 3297
Since you want to change only the value of the control id
, you should use patchValue
instead of setValue
method to modify the value of that formControl.
this.subcategoryForm.patchValue({
id:res.result.Name
});
if you want to use setValue
method, you can call it from the formControl id
:
this.subcategoryForm.controls['id'].setValue(res.result.Name);
Upvotes: 2