Clear input value at material angle

Asked

Viewed 405 times

0

I have a input in Angular Material:

<mat-form-field 
    class="width-layout p-0 col-xs-12 col-sm-4 col-md-4 col-lg-4"
    [class.mat-form-field-invalid]="errorValue" appearance="outline">
    <mat-label [class.input_disabled]="isDisabled">Numero</mat-label>
    <input type="text" [readonly]="read" 
        matInput 
        formControlName="numero" 
        name="numero" 
        id="numero" 
        placeholder="numero" 
        (change)="valida($event.target.value)" />
</mat-form-field> 

Where it is only enabled when you click on one checkbox, if the checkbox is enabled, it can change the initial value, if it is disabled, the input is disabled with the initial value.

When I click to enable the input, I put value there, and then disable it, it goes back to normal value, but when I enable it again, the input goes back to the previous value I put, and not Zera.

I tried to leave the input empty like this:

if (checked === true) {
  this.couponForm.controls.numero.enable();
  (document.getElementById('numero') as HTMLInputElement).value = '';
}

It’s even worthless, but when I mouse input it already shows the previous value, and not the input with the empty value as it should be.

  • 3

    Because it doesn’t make a Property Binding input to better control this?

  • @Leandrade could give me an example of how to use in my problem?

  • 1

    I would need to see how the TS is, just with these code has no idea.

  • @Leandrade understood, but I just used and it didn’t work. After I put a value and disable and enable again, will the value I entered in the input, not what I changed in ts

  • I would need to see how the code is like I said, because if you did the Property Binding in the input, in the checkbox click function just reset the values of the property you did Binding.

1 answer

3

Hello.

From what I’ve seen you working with Reactforms, that’s good. So let’s answer:

1º I changed the responsibility of "change" to Checkbox:

<mat-checkbox formControlName="checkbox"  [checked]="true" (change)="change($event.checked)" >Check me!</mat-checkbox>

2º I changed the function and now in case every time the Checkbox is true the input is enabled if false input back to value " " and disables the form input.

change(checked: any){
    if(checked){
      this.form.controls['numero'].enable();
    } else if(!checked){
    this.form.controls['numero'].setValue('');
    this.form.controls['numero'].disable();
    }
  }

In case you have any doubts just say the word.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.