How to disable a input in angular2
Asked Answered
H

15

179

In ts is_edit = true to disable...

<input [disabled]="is_edit=='false' ? true : null" id="name" type="text" [(ngModel)]="model.name" formControlName="name" class="form-control" minlength="2">

I just simply want to disable a input based on true or false.

I tried following:

[disabled]="is_edit=='false' ? true : null"
[disabled]="is_edit=='true'"
[disabled]="is_edit"
Halutz answered 11/2, 2017 at 17:48 Comment(2)
You already asked this question, and already had an answer, but then deleted the question. Again, open your browser console to notice the errors, fix them (i.e. use name and not formControlName), and then, it works: plnkr.co/edit/al2IkGkaZKpdLKKTfvKh?p=previewGuaco
The real problem here is that you're mixing template-based forms with reactive forms. Use one or the other, not both. @AJT_82 has the correct answer.Grondin
A
413

Try using attr.disabled, instead of disabled

<input [attr.disabled]="disabled ? '' : null"/>
Anny answered 3/5, 2017 at 16:48 Comment(10)
Setting attr value to null in order to NOT add the attr to element - looks like a hack - but it actually works, and even makes sence, in a hindsight.Flattery
disabled equals to true or falseSexism
Thank you for an answer that actually works! So why does attr.disabled work when disabled does not?Brigandine
Why angular document didn't say anything about this?Maher
While this works, it's a hack that doesn't address the real problem of mixing template-based forms with reactive forms. The OP should be using one or the other, not both.Grondin
<input [attr.disabled]="disabled || null"/> I think work alsoUnwise
This does not work in more recent versions of Angular. You can use [disabled]="disabled".Countershaft
Importante note: [attr.disabled]=false won't work, it has to be null. Don't ask me whyAncelin
this is not a good approach, because the user can delete this attribute via the browser, in which case it will change in the data in the model?Tranche
The currently recommended approach when using reactive forms (to avoid 'changed after checked' errors) is to set up a disabled property in your component class and the disabled attribute will be set in the DOM for you, more at https://mcmap.net/q/87793/-how-to-disable-a-input-in-angular2Bricklayer
A
56

If you want input to disable on some statement. use [readonly]=true or false instead of disabled.

<input [readonly]="this.isEditable" 
    type="text" 
    formControlName="reporteeName" 
    class="form-control" 
    placeholder="Enter Name" required>
Ataghan answered 7/11, 2018 at 11:32 Comment(3)
Reactive-friendly solution.Slemmer
This is correct. For me [attr.disabled]="disabled" worked one-way only i.e. input stayed in initial disabled/enabled stateDisputable
The currently recommended approach when using reactive forms (to avoid 'changed after checked' errors) is to set up a disabled property in your component class and the disabled attribute will be set in the DOM for you, more at https://mcmap.net/q/87793/-how-to-disable-a-input-in-angular2Bricklayer
H
46

I think I figured out the problem, this input field is part of a reactive form (?), since you have included formControlName. This means that what you are trying to do by disabling the input field with is_edit is not working, e.g your attempt [disabled]="is_edit", which would in other cases work. With your form you need to do something like this:

toggle() {
  let control = this.myForm.get('name')
  control.disabled ? control.enable() : control.disable();
}

and lose the is_edit altogether.

if you want the input field to be disabled as default, you need to set the form control as:

name: [{value: '', disabled:true}]

Here's a plunker

Hydromel answered 11/2, 2017 at 18:21 Comment(1)
Disabling an input means disabling its validations as well. This one is the only answer that achieves this goal and properly disable the input. This is the correct answer.Koralle
H
37

You could simply do this

<input [disabled]="true" id="name" type="text">
Hiedihiemal answered 8/3, 2018 at 9:8 Comment(6)
While this works, it suggests that "false" would enable the control, which it doesn´t since the presence of the disabled attribute is what diabled the control, not the value.Chromium
@Mecaveli, setting [disabled] to false actually enables the control. <input [disabled]="false" id="name" type="text"> makes the input field enabled. You could check over your angular application.Hiedihiemal
Just to correct myself here: As i learned, [disabled] doesn´t actually control the "disabled" html attribute value like [attr.disabled] would. Therefor, [disabled]="false" works although "false" as value for the html attribute "disable" would not.Chromium
So in all, you should actually use your editor and try it out before bringing up a counter point.Hiedihiemal
Indeed, sorry for downvoting unfortunately can´t undo it now. Was misusing [attr.disabled] for years thinking (or rather not much thinking) it´s equal to [disabled]...Chromium
This needs more context.Fulminant
K
15
<input [disabled]="is_edit" id="name" type="text">
<button (click)="is_edit = !is_edit">Change input state</button>

export class AppComponent {
  is_edit : boolean = false;
}
Kattie answered 11/2, 2017 at 18:22 Comment(2)
If you put console log in the isDisabled method, there are hundreds of console log are executed. If there is a complex logic in the isDisabled method, it might be a problem. So I am not sure this is a good solution.Preponderance
Do not put dynamic checking into Angular variables or you get an infinite loop. You can use [disabled]="is_edit" directly. Why the isDisabled() function?Infinitesimal
G
7

I presume you meant false instead of 'false'

Also, [disabled] is expecting a Boolean. You should avoid returning a null.

Gilberte answered 11/2, 2017 at 17:51 Comment(0)
E
4

I prefer this solution

In HTML file:

<input [disabled]="dynamicVariable" id="name" type="text">

In TS file:

dynamicVariable = false; // true based on your condition 
Eger answered 12/7, 2019 at 12:37 Comment(0)
B
4

Actually, the currently recommended approach when using reactive forms (in order to avoid 'changed after checked' errors) is not to use the disabled attribute with a reactive form directive. You should set up disabled property of this control in your component class and the disabled attribute will actually be set in the DOM for you.

<div>
      <form [formGroup]="form">
    <p>
        <input matInput type="text" placeholder="Name" formControlName="name"/>
    </p>
    </form>
</div>

and the component code:

form: FormGroup;
  public is_edit: boolean = true;
  constructor(
    private fb: FormBuilder
    ) {
    
  }

  ngOnInit() {
    this.form = this.fb.group({
      name: [{value: '', disabled: !this.is_edit}, [Validators.required, Validators.minLength(2)]],
    });
  }

Here is a plunker with the working code: http://plnkr.co/edit/SQjxKBfvvUk2uAIb?preview

Bricklayer answered 10/10, 2020 at 8:39 Comment(0)
N
3

A note in response to Belter's comment on fedtuck's accepted answer above, since I lack the reputation to add comments.

This is not true for any of which I am aware, in line with the Mozilla docs

disabled equals to true or false

When the disabled attribute is present the element is disabled regardless of value. See this example

<input placeholder="i can be changed"/>
<input disabled placeholder="i can NOT be changed"/>
<input disabled="true" placeholder="i can NOT be changed"/>
<input disabled="false" placeholder="i can NOT be changed"/>
Nephrolith answered 3/1, 2018 at 20:32 Comment(1)
that is true and wholly true for pure Html, but for angular, you have to provide a boolean value for disabled especially when you are doing two way binding.Hiedihiemal
L
2

Demo

make is_edit of type boolean.

<input [disabled]=is_edit id="name" type="text">

export class App {
  name:string;
  is_edit: boolean; 
  constructor() {
    this.name = 'Angular2'
    this.is_edit = true;
  }
}
Lurdan answered 11/2, 2017 at 17:55 Comment(0)
B
2

What you are looking for is disabled="true". Here is an example:

<textarea class="customPayload" disabled="true" *ngIf="!showSpinner"></textarea>
Brimmer answered 22/8, 2017 at 21:24 Comment(1)
This is incorrect, the HTML and DOM disabled attribute is a "boolean attribute" which means only the attribute name needs to be specified - or its value must equal disabled, e.g. disabled="disabled" - it does not recognize the values of true` or false - so disabled="false" will still cause the element to be disabled.Mohammed
S
2

Disable TextBox in Angular 7

<div class="center-content tp-spce-hdr">
  <div class="container">
    <div class="row mx-0 mt-4">
      <div class="col-12" style="padding-right: 700px;" >
          <div class="form-group">
              <label>Email</label>
                <input [disabled]="true" type="text" id="email" name="email" 
                [(ngModel)]="email" class="form-control">
          </div>
     </div>
   </div>
 </div>

Sennet answered 6/6, 2019 at 11:35 Comment(0)
K
1

Disabled Select in angular 9.

one thing keep in mind disabled work with boolean values in this example, I am using the (change) event with the select option if the country is not selected region will be disabled.

find.component.ts file

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-find',
  templateUrl: './find.component.html',
  styleUrls: ['./find.component.css']
})
export class FindComponent implements OnInit {
  isCountrySelected:boolean;

  constructor() { }
  //onchange event disabled false
 onChangeCountry(id:number){
   this.isCountrySelected = false;
 }
  ngOnInit(): void {
    //initially disabled true
    this.isCountrySelected = true;
  }

}

find.component.html

//Country select option
<select  class="form-control"  (change)="onChangeCountry()" value="Choose Country">
                    <option value="">Choose a Country</option>
                    <option value="US">United States</option>
                     
</select>
//region disabled till country is not selected 
<select class="form-control" [disabled]="isCountrySelected">
                    <option value="">Choose a Region</option>
                    <option value="">Any regions.</option>
                    
                </select>
Kinsey answered 28/6, 2020 at 6:59 Comment(0)
H
0

And also if the input box/button has to remain disable, then simply <button disabled> or <input disabled> works.

Hunfredo answered 9/7, 2019 at 9:58 Comment(0)
T
-2

can use simply like

     <input [(ngModel)]="model.name" disabled="disabled"

I got it like this way. so i prefer.

Togs answered 8/8, 2019 at 6:21 Comment(1)
This is not setting the disabled attribute dynamicallyAnnul

© 2022 - 2024 — McMap. All rights reserved.