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
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>
This works for me on Angular 8 project. Hope it helps.
<select [attr.disabled]="!name.valid ? 'disabled' : null" formControlName="gender">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With