What I want to achieve: I want pre-populated data in my form and I also want to use formControlName as I want the data too.
My html file -
<div >
<p >Add New Result</p>
<div >
<div >
<form (ngSubmit)="editStudent()" [formGroup]="studentEditForm" name="myForm">
<div >
<label for="roll-no" >Roll No.</label>
<input type="number" id="roll-no" name="rollno" formControlName="rollno" value="{{student.rollNo}}" placeholder="{{student.rollNo}}" autocomplete="off" required>
</div>
<div >
<label for="name" >Name</label>
<input type="text" id="name" name="name" formControlName="name" value={{student.name}} required>
</div>
<div >
<label for="email" >Email address</label>
<input type="email" id="email" name="email" formControlName="email" value={{student.email}} required>
</div>
<div >
<label for="score" >Score</label>
<input type="number" id="score" name="score" formControlName="score" value={{student.score}} required>
</div>
<button type="submit" ng-click="submitForm(myForm.$valid)">Submit</button><button type="submit" >Clear</button>
</form>
</div>
<div ></div>
<div ></div>
</div>
</div>
In Input Tag, I want to use value attribute so I can get a default value but I get Empty fields and I think it is because formControlName is controlling the data in my form. Is there a way to get pre-populated data using value attribute along with formControlName attribute?
Placeholder attribute works fine but I want a default value.
CodePudding user response:
if you want a default value simply initialize the form with values, for example:
form = new FormGroup({
name: new FormControl('defaultNameValue'),
email: new FormControl('defaultEmailValue')
})
CodePudding user response:
You should be doing it in you component instead of using value attribute. While defining the form example
studentEditForm= new FormGroup({
rollNo: new FormControl(this.student.rollNo)
})
or if student data is not available at the time of definition then use formcontrol.setValue after you initialize the student data something like
this.studentEditForm.controls.rollNo.setValue(this.student.rollNo)
CodePudding user response:
used value and CVA to control value
try this :
studentEditForm = new FormGroup({
score: new FormControl(VALUE),
});
CodePudding user response:
Using the value
and the CVA (Control Value Accessor: formControlName, formControl, and ngModel) to control the value of the input will override each other each time you change anyone of them.
Instead, it's better to rely only on one of them. If the CVA is used, then you can pass an initial value (default value) to the form-control while defining it:
studentEditForm = new FormGroup({
score: new FormControl(YOUR_INITIAL_VALUE),
});
For more info, check here how Angular passes the value from CVA to the value
property when using both of them:
default_value_accessor.ts