如何使用控制台开发工具更新 Angular 4+ 表单值?

2023-12-14

我正在尝试使用控制台(开发工具)填写 Angular 4+ 表单。

这就是我现在正在做的事情:

function fillForm(){
    let el = document.querySelector('input[ng-reflect-name="my_input"]');
    let elProbe = ng.probe(el);
    elProbe._debugContext.component.value = 'new-value';
}

我尝试使用的一些参考资料(如果对任何人有帮助的话):

  • https://juristr.com/blog/2016/02/debugging-angular2-console/
  • 从控制台触发角度变化检测

有两种选择。第一个是使用绑定到表单的组件属性,它需要手动更改检测触发。第二个是使用与输入关联的表单控件,并且不需要手动更改检测。

两者都不是更好。

对于第一个选项,请参阅@yurzui 的回答。这是第二个选项的答案 -直接更新表单控件无需变更检测:

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');
}

在这种情况下,您不需要更改检测,因为当您调用setValue直接在控件上通知valueAccessor关于变更:

FormControl.prototype.setValue = function (value, options) {
  ...
  this._onChange.forEach(function (changeFn) { 
      return changeFn(_this._value, options.emitViewToModelChange !== false); });

where changeFn是添加到的订阅者setUpContorl功能:

  control.registerOnChange((newValue: any, emitModelEvent: boolean) => {
    // control -> view
    dir.valueAccessor !.writeValue(newValue);

哪个调用writeValue直接在访问器上,然后将值写入输入:

export class DefaultValueAccessor implements ControlValueAccessor {
  ...

  writeValue(value: any): void {
    const normalizedValue = value == null ? '' : value;
    this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', normalizedValue);
  }

您可能还会发现这篇文章很有用

关于调试 Angular 应用程序您需要了解的一切

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用控制台开发工具更新 Angular 4+ 表单值? 的相关文章