Angular 具有 keydown.space 和 keydown.tab 的三元条件

Angular ternary condition with keydown.space and keydown.tab

我想要的是检查输入类型是否属于特定类型,然后才应用 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">

结果:

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

不检查它,如果你在三元中使用 true 而不是 false,它可能会起作用。


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

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

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

您正在使用 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">

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