Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

disable select in angular2

I am writing angular2 app. I need all my buttons and select with be disabled and then I need to enable them. I want to do that by using my class field butDisabled but with no luck. I have this code:

 @Component({
  selector: 'my-app',
  template:`
    <h1>Disable Enable</h1>
    <h2> this is a disabled select </h2>
    <select type="number" [(ngModel)]="levelNum" (ngModelChange)="toNumber()" disabled>
      <option *ngFor="let level of levels" [ngValue]="level.num">{{level.name}}</option>
    </select>
     <h2> this is a disabled button </h2>
    <button type="button" class="btn btn-default {{butDisabled}}">Disabled</button>

    <h2> Why can't I disable the select the same way? </h2>
    <select type="number" [(ngModel)]="levelNum" (ngModelChange)="toNumber()" class="{{butDisabled}}">
      <option *ngFor="let level of levels" [ngValue]="level.num">{{level.name}}</option>
    </select>


  `,
})
export class AppComponent {
  butDisabled = "disabled";
  levelNum:number;
  levels:Array<Object> = [
      {num: 0, name: "AA"},
      {num: 1, name: "BB"}
  ];

}

I don't understand why I can't use the {{butDisabled}} to disable the select. What Am I doing wrong? Thanks a lot

here is a plunker

like image 695
Noa Avatar asked Jul 14 '16 14:07

Noa


2 Answers

Even though it is said to use [disabled], it didn't work for me. I didn't figure it out.

But actually <select> and <option> are html elements, not angular elements. And to disable those elements in the original way, you can simply use disabled in the <select> tag.

To differentiate now, you can use a ng-container like this:

<ng-container *ngIf="element.isEditable === true; else notEditable"> 
    <select> 
        <option>
            ...
        </option>
    </select>
</ng-container>

<ng-template #notEditable> 
    <select disabled> 
        <option>
            ...
        </option>
    </select>
</ng-template>
like image 174
IonicMan Avatar answered Oct 24 '22 04:10

IonicMan


This works for me on Angular 8 project. Hope it helps.

<select [attr.disabled]="!name.valid ? 'disabled' : null" formControlName="gender">
like image 45
Karthikeyan Vellingiri Avatar answered Oct 24 '22 03:10

Karthikeyan Vellingiri