Is there a shortcut way to autofill a form using Angular?

Viewed 468

I'm on a project where I will be adding a receipt that will be shown after the user has submitted a form. There is no efficient way to test the form as I would have to fill in the form everytime to confirm that the questions and answers makes their way into the receipt.

I want to create a temporary single method autoFill() that is tied to an anchor element in order to automatically fill in the form with answers. In Javascript I can do this with something like document.getElementById('id').value = myValue, but in Angular there seems to be no way to set an input element's value this way. Instead, I would have to rewrite all the input fiels in the component by writing input setups. All the examples I have seen includes rewriting the component itself, like this:

@Component({
  selector: 'app-click-me',
  template: `
    <button (click)="onClickMe()">Click me!</button>
    {{clickMessage}}`
})
export class ClickMeComponent {
  clickMessage = '';

  onClickMe() {
    this.clickMessage = 'You are my hero!';
  }
}

But I don't want to change the original code.

I also don't want to install any dependencies like Selenium, although it would be a great choice.

Isn't there an easier way?

This is something like I would be looking for to be able to call in an Angular project:

autoFill() {
    document.getElementById('input1').value = "myTextValue";
    document.getElementById('input2').value = "Dropdown2";
  
    var radioElements = document.getElementsByName("input3");
  
    for (var i=0; i<radioElements.length; i++) {
      if (radioElements[i].getAttribute('value') == 'Radio3') {
        radioElements[i].checked = true;
      }
    }
  }
1 Answers

if you're using reactive-forms to manage your angular forms you can, according to this, declare your formcontrol in your template :

<form [formGroup]="myForm">
<input formControlName="input1">
</form>

and in your typescript :

this.myForm.input1.setValue('');

or

this.myForm.patchValue({input1: '', input2 : ''});

NB: before being able to patch/modify the value of your input, you need to declare it as seen in the documentation, my favorite way is the following :

export class MyComponent {
   myForm: FormGroup

   constructor(private fb: FormBuilder){
     this.myForm = this.fb.group({
       input1 : ['default value'],
    ...
     })
   }
}
Related