One of the most common HTML elements which we use for getting user feedback oftentimes need to be disabled. We will see how we can disable Angular HTML Elements programmatically using different types of HTML Elements.
We will be using a simple condition, where we will use a value from the component, which will be set programmatically.
Since we will be taking a look at how to disable Angular HTML Elements, we need a component to drive the data.
Our component will look like so:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
public disableInputField = false;
public disableButtonField = false;
public disableTextareaField = false;
public disableMaterialInputField = false;
public disableSelectField = false;
}
All you need to do is to hook the disabled property to the two-way bound value of the component.
<input type="text"
[disabled]="disableInputField"
placeholder="Input Field" />
<button (click)="disableInputField = true">
Disable Angular Input Field
</button>
For this, all you need to do is to hook the disabled property of the button to the component’s property like so:
<button (click)="disableButtonField = true">
Disable Angular Button
</button>
<button [disabled]="disableButtonField">
Disable Angular Button
</button>
This is similar to how you would disable Angular input element. You can use this option:
<textarea
type="text"
[disabled]="disableTextareField"
placeholder="Textarea Field"
></textarea>
<button (click)="disableTextareField = true">
Disable Angular TextArea Field
</button>
First of all, you will need to wrap the input element inside mat-form-field and then simply do this:
<mat-form-field>
<input
matInput
type="text"
[disabled]="disableMaterialInputField"
placeholder="Material Input Field"
/>
</mat-form-field>
<button (click)="disableMaterialInputField = true">
Disable Angular Material Field
</button>
For this one, always remember that the Angular select is what will have the bound value, and hence, it is the one which you should have as the target to disable.
You can do it like so:
<select
name=""
id=""
[disabled]="disableSelectField"
placeholder="Select Field"
>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button (click)="disableSelectField = true">
Disable Angular Select Field
</button>
As you can see, it is so easy to disable Angular HTML elements, as needed.
With that, happy coding and