角4-5:自定义指令在* ngFor中不起作用

时间:2018-11-14 10:58:29

标签: angular angular-directive

我创建了一个自定义指令,仅允许在文本框中输入数字值。正常情况下,它工作正常,但是只要我在* ngFor内部尝试使用我们,它就根本无法工作。

此处 OnlyNumber 是自定义指令。

import { Directive, ElementRef, ChangeDetectorRef, Input, HostListener } from "@angular/core";
import { NgControl } from "@angular/forms";

@Directive({
  selector: '[OnlyNumber]' 
})

export class OnlyNumberDirective {
  constructor(private cdRef: ChangeDetectorRef, private el: ElementRef, private ngControl: NgControl) { }

  @Input() OnlyNumber: boolean;

  @HostListener('keydown', ['$event']) onKeyDown(event) {    
    let e = <KeyboardEvent> event;
    if (this.OnlyNumber) {
      if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
        // Allow: Ctrl+A
        (e.keyCode === 65 && (e.ctrlKey || e.metaKey)) ||
        // Allow: Ctrl+C
        (e.keyCode === 67 && (e.ctrlKey || e.metaKey)) ||
        // Allow: Ctrl+V
        (e.keyCode === 86 && (e.ctrlKey || e.metaKey)) ||
        // Allow: Ctrl+X
        (e.keyCode === 88 && (e.ctrlKey || e.metaKey)) ||
        // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
          // let it happen, don't do anything
          return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
      }
  }
}

无效代码

<tbody id="quote_type1_tbody" *ngFor="let loTempQuoteProduct of this.moTempQuoteProductList"> 
     <tr>
         <td> 
            <input type="text" id="ListCost" maxlength="8" 
                class="form-control m-input" placeholder="Enter list cost"
                [ngModel]="TempProduct.Cost"
                (ngModelChange)="TempProduct.Cost = $event;" 
                OnlyNumber="true">
         </td>
     </tr>
</tbody>

工作代码-ngFor之外

<input type="text" id="ListCost" maxlength="8" 
            class="form-control m-input" placeholder="Enter list cost"
            [ngModel]="TempProduct.Cost"
            (ngModelChange)="TempProduct.Cost = $event;" 
            OnlyNumber="true">

您的宝贵时间和答复将不胜感激。

多谢指教!

1 个答案:

答案 0 :(得分:0)

在ngOnInit()中编写指令逻辑