1

i want to set the value of the text box on click of some other button which is present outside the form, how can i do it

<form [formGroup]='student' (ngSubmit)='click()'>
<input type='text' formControlName='name'
<input type='submit' value='submit'>
</form>
<input type='button' (click)='setValueOfTextbox()' value='some other button'>

now, when i click on this button and try to set the value, i am not able to do this

student:FormGroup

setValueOfTextbox(){
this.student.controls.name.setValue('foo')
}

how can i set the value of a button placed in the reactive form?

Lijin Durairaj
  • 4,910
  • 15
  • 52
  • 85
  • Does this answer your question? [How to set value to form control in Reactive Forms in Angular](https://stackoverflow.com/questions/55275025/how-to-set-value-to-form-control-in-reactive-forms-in-angular) – wentjun Jan 02 '20 at 19:08

1 Answers1

4

Your code works just fine, please initialize your form group and the form controls

ngOnInit() {
  this.student = new FormGroup({
    name: new FormControl()
  })
}

setValueOfTextbox(){
  this.student.controls.name.setValue('foo')
}

https://stackblitz.com/edit/angular-kwcrcp?file=src%2Fapp%2Fapp.component.ts

Ashish Ranjan
  • 12,760
  • 5
  • 27
  • 51
  • well, the code was just a snippet of a bigger and complex code, how can i set a value of checkbox? is it the same way? – Lijin Durairaj Mar 19 '19 at 08:00
  • i added one checkbox control and tried this and it did not work, this.student.controls.gender.setValue('true'); could you please help on this? – Lijin Durairaj Mar 19 '19 at 08:01
  • please see my updated stackblitz https://stackblitz.com/edit/angular-biwuvy?embed=1&file=src/app/app.component.ts – Lijin Durairaj Mar 19 '19 at 08:07
  • @LijinDurairaj: It will work the same, in your stackblitz example you haven't created a formControl for gender: Check this: https://stackblitz.com/edit/angular-r6eelg?file=src%2Fapp%2Fapp.component.ts – Ashish Ranjan Mar 19 '19 at 08:11