Cristian De Vecchi
Cristian De Vecchi

Reputation: 25

I've to disabled a FormControl but keep validation

I' ve this FormGroup:

this.fb.group({
    a: ["", Validators.required],
    b: ["", Validators.required],
    c: [{value: "", disabled: true}, Validators.required]
});

In template, filling the first 2 control (a and b), generate value for the third one (c) at valueChanges.subscribe() methods.

Below in the form i've a button for next pages. This should be disabled until form is valid (3 controls not empty), but for now it doesn't work as i wish because the third control is disabled and so the validation for that field is skipped. The result is that after the second control is filled, even if my generation function failed and the control "c" remain empty, the button is enabled.

I've seen on other posts the usage of [attr.disabled] but in Angular 15 it doesn't seem to work. Is there another way to disable a field in template keeping validation running?

I'm trying to find a solution different to setting field's error into the generation function.

Upvotes: 0

Views: 398

Answers (2)

Ricudo
Ricudo

Reputation: 345

I think you can reach it by keep the control enabled and just change it's styles by adding/removing next class(if we talk about <input>):

.disabled-input {
    pointer-events: none;
    cursor: not-allowed;
    // you styles for disabled input, for example:
    opacity: 0.5;
    background-color: #f0f0f0;
    color: #808080;
}

Upvotes: 0

Eliseo
Eliseo

Reputation: 58019

It's looks like a bug, see this discussion in github

But you can use a directive as temporal solution

//I use "disable" as selector instead of disabled
@Directive({
  selector: '[disable]',
  standalone:true
})
export class CustomDisabledDirective implements AfterViewInit {
  _disable:boolean
  @Input('disable') set _(value:boolean)
  {
    this._disable=value;
    this.ngAfterViewInit();
    
  }
  constructor(private elementRef:ElementRef) { }
  ngAfterViewInit()
  {
    if (this._disable)
    this.elementRef.nativeElement.setAttribute('disabled','true')
    else
    this.elementRef.nativeElement.removeAttribute('disabled')
  }

Upvotes: 0

Related Questions