Angular ControlGroup验证不重置值

问题描述 投票:2回答:1

一旦用户在UI中输入值,我就无法重置验证。

在调试器中,我可以看到值传递到onModelChange,它永远不会重置。我希望验证知道控件中有一个值而不是阻塞它并将值设置为IsInvalid为false。

我需要在[formControl]的html中添加什么来验证值?

输入值后,应删除UI红色框

Red box should be removed once value is enter debugger

HTML:

<div contenteditable="true"
     style="width: 100% !important; overflow: hidden"
     class="form-control sentence-part-values-inline sentence-part-values-inline-textbox-number"
     [attr.id]="editorId">
</div>

打字稿:

@Output() public modelchange: EventEmitter<any> = new EventEmitter();
    public onModelChange(): void {
        this.validate();
        this.modelchange.next(this.getModel());
    }  

    initControlGroup(fb: FormBuilder) : FormGroup {
        return fb.group({
            "value": ['', Validators.required]        
        });
    }



(<any>window).CKEDITOR.instances[this.editorId].on("change", () => {
                    self.model.Value = (<any>window).CKEDITOR.instances[self.editorId].getData();
                    self.onModelChange();
                });

将formControl设置为value更新html

<div contenteditable="true"
     style="width: 100% !important; overflow: hidden"
     class="form-control sentence-part-values-inline sentence-part-values-inline-textbox-number"
     [formControl]="value"
     [attr.id]="editorId">
</div>

ts班

 interface SentencePartModel extends SentencePartModelBase {
        Type: SentencePartType;
        Value: string;
    }
angular typescript angular-forms
1个回答
0
投票

很高兴看到完整的代码,但我相信你需要创建一个实现ControlValueAccessor的组件(正如许多注释所示),你正在尝试使用div元素作为一个不起作用的表单控件,您需要的是创建一个自定义表单控件并在此组件中实现您的编辑器(请参阅https://alligator.io/angular/custom-form-control/)。

您的组件应如下所示:

@Component({
  selector: 'my-component',
  ...,
  providers: [
    { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MyComponent), multi: true }
  ]
})
export class MyComponent implements OnInit, ControlValueAccessor {

  @Input() disabled = false;

  theModel: string;
  onChange: (value: string) => {};
  onTouched: () => {};

  ...

  writeValue(value: string): void {
    // allows angular to bind to the model (theModel)
    this.theModel = value;
    this.onChange(this.value);
  }

  registerOnChange(fn: (value: string) => void): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: () => void): void {
    this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }
}

您的HTML模板将构成此组件的模板,您可以像现在一样将绑定添加到change事件中,在更改事件中,您可以调用this.onChange(value)来触发模型更新

您的用法是在父组件中创建form并在formControlName上设置my-component

父组件模板:

<!-- where myEditor is the name of the form control in your FormGroup -->
<my-component formControlName="myEditor"></my-component>

希望这可以帮助

© www.soinside.com 2019 - 2024. All rights reserved.