Reputation: 1
I'm working on a project where I have an input field. Below this input field, there is a switch, if the switch is disabled, the input field is readonly
.
Currently, I have the following solution, which does the job but is not nice. (If I use the switch, the input field disparat for some seconds):
app.component.html
<input *ngIf="isReadonly" readonly type="text"[formControl]="title">
<input *ngIf="!isReadonly" type="text" [formControl]="title">
<div class="switch form-switch" role="switch">
<input type='checkbox' id='switch' (click)="switch()">
<label for='title_switch'>{{'CUSTOM_TITLE_SWITCH'|translate}}</label>
</div>
app.component.ts
isReadonly = true
switch() {
this.isReadonly = !this.isReadonly
}
As I said, this solution works but it's not nice. Does anyone have a better idea?
Thanks!
Upvotes: 0
Views: 7712
Reputation: 4110
There are many ways to achieve this.
Here is one of them using a ngModel
binding on your checkbox
. You can use binding too on the readonly
property (no need to use a *ngIf
to toggle the input).
Html:
<input [readonly]="isReadonly" type="text" value="Text example">
<div class="switch form-switch" role="switch">
<input type='checkbox' id='switch' [(ngModel)]="isReadonly">
<label for='title_switch'>Switch</label>
</div>
Typescript:
export class AppComponent {
public isReadonly: boolean = true;
}
Here is a stackblitz: https://stackblitz.com/edit/angular-tabcjw
If you are using you inputs inside a formGroup
simply add [ngModelOptions]="{standalone: true}"
on your checkbox
(as explained here: Use of [(ngModel)] within FormGroup):
<div class="switch form-switch" role="switch">
<input type='checkbox' id='switch' [(ngModel)]="isReadonly" [ngModelOptions]="{standalone: true}">
<label for='title_switch'>Switch</label>
</div>
Upvotes: 0
Reputation: 6286
Have you tried to bind the readonly
attribute?
<input [readonly]="isReadonly" type="text" [formControl]="title">
Upvotes: 2