当我尝试迭代ngFor循环时,Angular 2+ attr.disabled不适用于div

Shr*_*tel 9 typescript ngfor angular

我正在预约预约应用程序,我正在显示使用*ngFor循环约会的时间段.

HTML

<div *ngFor="let item of allTimeSlots">
    <div class="col-sm-3">
        <div class="choice" data-toggle="wizard-slot" [attr.disabled]="item.status" (click)="slotSelected($event)">
            <input type="radio" name="slot" value="{{item.timeSlot}}">
            <span class="icon">{{item.timeSlot}}</span> {{item.status}}
        </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

打字稿

for (var index = 0; index < this.totalMinutes; index += 15, i++) {
  this.allTimeSlots[i] = new allTimeSlots("", false);

  this.allTimeSlots[i].timeSlot = (hour <= 12 ? hour : hour - 12) + ":" + (minute <= 9 ? ("0" + minute) : minute) + " " + ampm;
  this.bookedTimeSlots.forEach(element => {
    if (this.allTimeSlots[i].timeSlot == element) {
      this.allTimeSlots[i].status = true;
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

这是时间段的屏幕截图,显示true时间段是否已预订,如果可用于调试,则显示为false. 在此输入图像描述

当我运行此代码时,它不会抛出任何错误,但会禁用所有div创建的元素*ngFor.我尝试使用*ngIf而不是禁用,它工作得很好.但问题是我想显示时隙是否可用.

baH*_*aHI 14

以这种方式使用它:

[attr.disabled]="isDisabled ? '' : null"
Run Code Online (Sandbox Code Playgroud)

只读。


0mp*_*rdy 13

用[disabled]而不是[attr.disabled]

这是因为[attr.disabled]="false"将添加disabled="false"到html中的元素,仍将禁用该元素

不会禁用元素的语法

<button>Not Disabled</button>
<button [disabled]="false">Not Disabled</button>
Run Code Online (Sandbox Code Playgroud)

将禁用元素的语法

<button disabled></button>
<button disabled="true"></button>
<button disabled="false"></button>
<button [attr.disabled]="true"></button>
<button [attr.disabled]="false"></button>
<button [disabled]="true"></button>
Run Code Online (Sandbox Code Playgroud)

disabled将禁用一个元素,无论它是真还是假,它的存在意味着该元素将被禁用.如果为false,Angular将不会添加该disabled元素.[disabled]="variable"variable

正如您在评论中提到的那样,您使用的是div元素而不是按钮,其中angular 2无法识别已禁用的元素.如果您要捕获click事件,我建议使用按钮,但如果不是,您可以执行以下操作:

<div [ngClass]="{ 'disabled': item.status }"></div>
Run Code Online (Sandbox Code Playgroud)

并有一个CSS类来显示预订的时间段.

有关详细信息,[ngClass]请参阅文档


Ara*_*ind 12

禁用不能用于div元素,仅适用于以下元素

<button>    
<fieldset>  
<input> 
<keygen>    
<optgroup>  
<option>    
<select>    
<textarea>  
Run Code Online (Sandbox Code Playgroud)

看到这个

因此,对于您的问题,您可以使用以下方法处理它:

<div 
  class="choice" 
  data-toggle="wizard-slot" 
  [class.disabled]="item.status" 
  (click)="slotSelected($event)">
  <input 
    type="radio" 
    name="slot" 
    value="{{item.timeSlot}}" 
    [disabled]="item.status">
  <span class="icon">{{item.timeSlot}}</span> {{item.status}}
</div>
Run Code Online (Sandbox Code Playgroud)

你应该添加样式

.disabled {
  cursor: not-allowed;
}
Run Code Online (Sandbox Code Playgroud)