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?

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

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?
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?
@LijinDurairaj: It will work the same, in your stackblitz example you haven't created a formControl for gender: Check this: stackblitz.com/edit/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.