Search code examples
angularangular6angular-forms

How to set value to a Reactive Form control in Angular6?


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?


Solution

  • 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