There are two options. The first one is to work with component property bound to a form and it requires manual change detection triggering. The second one is to work with the form control associated with the input and it doesn't require manual change detection.
Neither is better.
For the first option see @yurzui's answer. Here is the answer for the second option - update the form control directly without the need for change detection:
function fillForm(){
let el = document.querySelector('input[ng-reflect-name="my_input"]');
let elProbe = ng.probe(el);
const NgControlClassReference = elProbe.providerTokens.find((p)=>{
return p.name === 'NgControl';
});
let directive = elProbe.injector.get(NgControlClassReference);
let control = directive.control;
control.setValue('some');
}
In this case you don't need change detection because when you call setValue
on the control directly it notifies valueAccessor
about the change:
FormControl.prototype.setValue = function (value, options) {
...
this._onChange.forEach(function (changeFn) {
return changeFn(_this._value, options.emitViewToModelChange !== false); });
where changeFn
is a subscriber added in the setUpContorl
function:
control.registerOnChange((newValue: any, emitModelEvent: boolean) => {
// control -> view
dir.valueAccessor !.writeValue(newValue);
which calls writeValue
on the accessor directly and it in turn writes the value into input:
export class DefaultValueAccessor implements ControlValueAccessor {
...
writeValue(value: any): void {
const normalizedValue = value == null ? '' : value;
this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', normalizedValue);
}
You also might find this article useful
Everything you need to know about debugging Angular applications