带有keydown.space和keydown.tab的三元角条件

时间:2018-07-31 07:36:16

标签: angular ternary-operator

我要检查的是输入类型是否仅是特定类型,然后应用keydown.spacekeydown.tab的检查

我尝试过的事情:

 <input (keydown.space)="locationUi.location_type=='video' ? $event.preventDefault() : false" (keydown.tab)="locationUi.location_type=='video' ? $event.preventDefault(): false" id="masked-input" [ngClass]="locationUi.location_type=='video' ? 'width-40':''" (input)="textInput()" type="{{locationUi.extra.field.type}}" name="inputOtherAdress" class="form-control" placeholder="{{locationUi.extra.field.placeholder}}"
            [required]="locationUi.enabled" [value]="locationUi.data" (input)="locationUi.data = $event.target.value">

结果:

这将禁用所有输入字段上的空格和制表符。

2 个答案:

答案 0 :(得分:1)

您使用的是false,而不是null,它应该可以正常工作。

 <input (keydown.space)="locationUi.location_type=='video' ? $event.preventDefault() : null" (keydown.tab)="locationUi.location_type=='video' ? $event.preventDefault(): null" id="masked-input" [ngClass]="locationUi.location_type=='video' ? 'width-40':''" (input)="textInput()" type="{{locationUi.extra.field.type}}" name="inputOtherAdress" class="form-control" placeholder="{{locationUi.extra.field.placeholder}}"
            [required]="locationUi.enabled" [value]="locationUi.data" (input)="locationUi.data = $event.target.value">

此外,更好的解决方案是通过控制器使用它。

答案 1 :(得分:0)

如果不进行检查,则在三元组中使用true而不是false可能会起作用。


但是,无论如何这应该在控制器中更好地处理。模板已经有相当多的逻辑,这使得整个内容真的很难看懂。

public onSpace(event: Event) {
  if (this.locationUi.location_type === "video") {
    event.preventDefault();
  }
}

<input (keydown.space)="onSpace($event)" … />