Angular 2/4:如何使用指令检查输入值的长度?

时间:2017-09-21 14:23:32

标签: angular typescript angularjs-directive angular2-directives

我创建了一个可以验证输入的自定义属性指令,它有没有值。请参考以下代码。

我不知道为什么如果条件不起作用,在console.log中它只显示0。我的代码有什么问题吗?

我也试过了其他角度的应用生命周期事件。

谢谢!

import { Directive, ElementRef, Input, AfterContentInit ,Renderer } from '@angular/core';

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

export class InputFocusedDirective implements AfterContentInit {
    public valLength;

    constructor(public el: ElementRef, public renderer: Renderer) {}

    ngAfterContentInit() {

        var valLength = this.el.nativeElement.value.length;
    consol.log("valLength "+ valLength );

        if (valLength > 0) {
           this.renderer.setElementClass(this.el.nativeElement.parentElement, 'focused', true);
        }


    }
}

3 个答案:

答案 0 :(得分:3)

如果你想要做的就是在输入中包含一些文本时将一个类应用于包含元素,那么你就不需要一个指令了。

<div id="i-contain-the-input" [ngClass]="{'focused': myInputValue && myInputValue.length > 0}">
  <input [(ngModel)]="myInputValue" type="text">
</div>
<!-- myInputValue needs to be declared in your component -->

但如果您绝对必须为此做出指示,请执行以下操作:

@Directive({
  selector: '[inputfocus]',
})
export class InputFocusedDirective {

  constructor(private el: ElementRef, private render: Renderer) {
  }

  @HostListener('change') onChange() {
    if (this.el.nativeElement.value.length > 0) {
      this.renderer.setElementClass(this.el.nativeElement.parentElement, 'focused', true);
    }
  }

}

答案 1 :(得分:2)

您可以在DoCheck中跟踪输入长度更改:

<强>指令

Directive({ selector: '[inputfocus]' })

export class InputFocusedDirective implements DoCheck
 {
   public valLength;
   @Input() inputfocus;
   constructor(public el: ElementRef, public renderer: Renderer) {}


   ngDoCheck(){
         let valLength = this.el.nativeElement.value.length;
         console.log("valLength "+ valLength );

        if (valLength > 0) {
           this.renderer.setElementClass(this.el.nativeElement.parentElement, 'focused', true);
        }
        else
        {
          this.renderer.setElementClass(this.el.nativeElement.parentElement, 'focused', false);
        }
    }
}

<强> HTML

<div>
   <input [inputfocus]="fname" name="name" [(ngModel)]="fname" type="text">
</div>

<强> CSS:

input{
  background-color:red;
}

.focused input{
  background-color:green;
}

stackblitz demo

答案 2 :(得分:1)

我创建了一个类似的例子。

import {Directive, ElementRef} from '@angular/core';

@Directive({
 selector: '[inputfocus]'
 })
export class DataDirective {

   constructor(private el: ElementRef) { 
     var elem = el.nativeElement.value;
    console.log(elem + "==> length = " + elem.length);
   }


}

在html部分

<input class="mask-text" value="hello" inputfocus type="text"/>

演示http://plnkr.co/edit/JX6P1vnqUJEzL94BOFuO?p=preview