角2/4:如何使用指令检查输入值的长度? [英] Angular 2/4 : How to check length of input's value using directive?
本文介绍了角2/4:如何使用指令检查输入值的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个可以验证输入的自定义属性指令,它是否有价值.请参考下面的代码.
I've created one custom attribute directive that can validate input, It has value or not. Please refer below code.
我不知道为什么条件不起作用,在console.log中它仅显示0.我的代码有什么问题吗?
I don't know why if condition is not working, in console.log it is showing 0 only. is there anything wrong in my code?
我也尝试了其他angular的应用程序生命周期事件.
I tried with other angular's app lifecycle event too.
谢谢!
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);
}
}
}
推荐答案
您可以在 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;
}
这篇关于角2/4:如何使用指令检查输入值的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文