Fill Angular form from developer console

Viewed 548

In Angular 8 I was able to do this:

const el = document.querySelector("#first-name);
if (!el) { console.warn(item.selector, 'not found'); return; }
const probe = ng.probe(el);
const ref = probe.providerTokens.find(p => p.name === 'NgControl');
const directive = probe.injector.get(ref);
directive.control.setValue("Johnnie");

This would find an input with a formControlName and Reactive Forms based code behind it, set its value, including triggering of any change detection in Angular.

In Angular 9 with Ivy this no longer works, as ng.probe has been removed in favor of other tooling, most notably ng.getComponent. However, that method seems mainly useful for getting actual Angular components, and I'm unsure how I can use that to edit form values and trigger change detection.

What would be the Angular 9 & Ivy way to do this?

1 Answers

This has worked for me, you just change the input value in plain JS and then trigger the change event. You can use the same event for multiple inputs.

const changeEvent = document.createEvent("HTMLEvents");
changeEvent.initEvent("change", false, true);

const el = document.querySelector("#first-name");
el.value = 3;
el.dispatchEvent(changeEvent);
Related