0

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!

2 Answers 2

2

Have you tried to bind the readonly attribute?

<input [readonly]="isReadonly" type="text" [formControl]="title">
Sign up to request clarification or add additional context in comments.

Comments

0

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>

2 Comments

No, I'll get this error:ngModel cannot be used to register form controls with a parent formGroup directive.
Yes it's because you use formGroup. You can add [ngModelOptions]="{standalone: true}" as described here: stackoverflow.com/questions/41549426/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.