如何在Angular8 Bootstrap datetime picker中仅为Inactive标签保留时间选择器
解决方案
你可以通过动态配置日期选择器参数+ 条件类控制的方式实现需求,不需要全局修改CSS,避免影响其他组件:
步骤1:修改HTML模板
给输入框动态绑定选择器配置,同时根据标签名判断是否为Inactive项:
<div class="col-6 {{isReadOnly ? 'link-disabled' : ''}}" *ngFor="let restrictValue of Restrictions;let i = index"> <div class="custom-control custom-switch"> <input type="checkbox" class="custom-control-input" id="{{restrictValue.id}}" [checked]="restrictValue.boolValue" (change)="restrictValue.boolValue = $event.target.checked" > <label class="custom-control-label" for="{{restrictValue.id}}">{{restrictValue.label}}</label> </div> <div class="form-group"> {{restrictValue.datetime}} <input type="text" class="form-control onlyDateTime" placeholder="{{restrictValue.label === 'Inactive' ? 'MM/DD/YYYY HH:MM AM/PM' : 'MM/DD/YYYY'}}" [disabled]="!restrictValue.boolValue" [(ngModel)]="restrictValue.datetime" (click)="dateRestriction(i)" [bsConfig]="restrictValue.label === 'Inactive' && restrictValue.boolValue ? {showTime: true, dateInputFormat: 'MM/DD/YYYY hh:mm A'} : {showTime: false, dateInputFormat: 'MM/DD/YYYY'}" [ngModelOptions]="{standalone: true}" > </div> </div>
步骤2:移除原有全局CSS
删除你现在写的全局隐藏时间选择器的CSS代码,避免和组件配置冲突。
如果你使用的组件版本不支持通过showTime参数控制,可改用CSS动态控制的方案:
- 在
dateRestriction方法里判断当前点击的是否为Inactive且已勾选的项,给全局根元素动态加/删show-inactive-time类:
dateRestriction(index: number) { const currentItem = this.Restrictions[index]; if (currentItem.label === 'Inactive' && currentItem.boolValue) { document.body.classList.add('show-inactive-time'); } else { document.body.classList.remove('show-inactive-time'); } // 原有逻辑保留 }
- 替换原有CSS为条件生效逻辑:
::ng-deep .bootstrap-datetimepicker-widget .list-unstyled li:nth-child(2) { display: none; } ::ng-deep body.show-inactive-time .bootstrap-datetimepicker-widget .list-unstyled li:nth-child(2) { display: block; }
内容的提问来源于stack exchange,提问作者Bhrungarajni
相关产品推荐
相关产品推荐

