简体   繁体   English

使 mat-slide-toggle 只读

[英]Make mat-slide-toggle read only

I am using mat-slide-toggle in my app & want to know if there's a way to make it read-only ie disable the slider.我在我的应用程序中使用 mat-slide-toggle 并想知道是否有办法使其只读,即禁用滑块。 I don't want to disable the whole component which is the result when I set the disabled property.我不想禁用整个组件,这是我设置 disabled 属性时的结果。 Is there any way to do this?有没有办法做到这一点?

as work around this you can add an ngModel and ngModelChange output to force the mat-slide to keep same value ( not perfect solution but it will work)作为解决此问题的方法,您可以添加ngModelngModelChange输出以强制 mat-slide 保持相同的值(不是完美的解决方案,但它会起作用)

<mat-slide-toggle [(ngModel)]="myModel" (ngModelChange)="keepIt($event)">
              </mat-slide-toggle>

on Ts file在 Ts 文件上

    keepIt(d){
       this.myModel=true    
    }

the other solution you can do is to remove the opacity from mat-disabled , that will make it look like an active slider and you can then add [disabled]="true"您可以做的另一个解决方案是从 mat-disabled 中删除不透明度,这将使它看起来像一个活动滑块,然后您可以添加 [disabled]="true"

::ng-deep .mat-slide-toggle.mat-disabled {
  opacity: 1 !important;
}

check this https://stackblitz.com/edit/angular-9zujdv?file=src%2Fapp%2Fslide-toggle-overview-example.html检查这个https://stackblitz.com/edit/angular-9zujdv?file=src%2Fapp%2Fslide-toggle-overview-example.html

You can also create a directive您还可以创建指令

@Directive({
  selector: '[disableToogle]'
})
export class DisableToogleDirective {
  @Input() set disableToogle(value:boolean)
  {
        this.slide.toggleChange.closed=value
  }
  constructor(private slide:MatSlideToggle) { }
}

You use as你用作

<mat-slide-toggle  [disableToogle]="variable">Slide me!</mat-slide-toggle>

See the stackblitz查看堆栈闪电战

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM