【问题标题】:angular - how to change inputfield to readonly with a switch角度 - 如何使用开关将输入字段更改为只读
【发布时间】:2020-10-08 05:03:03
【问题描述】:

我正在做一个有输入字段的项目。在这个输入栏下方,有一个开关,如果开关被禁用,则输入栏为readonly

目前,我有以下解决方案,它可以完成这项工作,但效果不佳。 (如果我使用开关,输入字段会相差几秒钟):

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
}

正如我所说,此解决方案有效,但效果不佳。有人有更好的主意吗?

谢谢!

【问题讨论】:

    标签: angular input switch-statement angular8 readonly


    【解决方案1】:

    有很多方法可以实现这一点。 这是其中一个在您的checkbox 上使用ngModel 绑定。您也可以在 readonly 属性上使用绑定(无需使用 *ngIf 来切换输入)。

    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>
    

    打字稿:

    export class AppComponent  {
      public isReadonly: boolean = true;
    }
    

    这是一个堆栈闪电战:https://stackblitz.com/edit/angular-tabcjw

    如果您在formGroup 中使用您的输入,只需在您的checkbox 上添加[ngModelOptions]="{standalone: true}"(如下所述: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>
    

    【讨论】:

    • 不,我会收到这个错误:ngModel cannot be used to register form controls with a parent formGroup directive.
    • 是的,因为你使用了formGroup。您可以添加[ngModelOptions]="{standalone: true}",如下所述:stackoverflow.com/questions/41549426/…
    【解决方案2】:

    您是否尝试绑定readonly 属性?

    <input [readonly]="isReadonly" type="text" [formControl]="title">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      • 2016-02-22
      • 2012-09-27
      • 2020-03-03
      • 2014-05-02
      • 2013-07-23
      相关资源
      最近更新 更多