本文介绍了如何使用控制台devtools更新角度4+表单值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在尝试使用控制台(devtools)填写Angular 4+表单.

I'm trying to fill a Angular 4+ form using console (devtools).

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

This is what I'm doing now:

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

我正在尝试使用一些参考(如果它可以帮助任何人):

Some references I'm trying to use (if it helps anyone):

  • https://juristr.com/blog/2016/02/debugging-angular2-console/
  • Trigger Angular change detection from console

推荐答案

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

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.

两者都不是更好.

关于第一个选项,请参见@yurzui的答案.这是第二个选项的答案-直接更新表单控件,而无需进行更改检测:

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

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

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

其中changeFn是在setUpContorl函数中添加的订户:

where changeFn is a subscriber added in the setUpContorl function:

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

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

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

关于调试的所有知识Angular应用程序

这篇关于如何使用控制台devtools更新角度4+表单值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 18:23