问题
I've created one custom attribute directive that can validate input, It has value or not. Please refer below code.
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?
I tried with other angular's app lifecycle event too.
Thanks!
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);
}
}
}
回答1:
You can track the input length changes in DoCheck:
Directive
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:
If all you are trying to do is apply a class to the containing element when an input has some text inside it, you do not need a directive for this.
<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 -->
But if you absolutely must make a directive for this, then do the following:
@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);
}
}
}
回答3:
I have created a similar example.
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);
}
}
in the html part
<input class="mask-text" value="hello" inputfocus type="text"/>
Demo http://plnkr.co/edit/JX6P1vnqUJEzL94BOFuO?p=preview
来源:https://stackoverflow.com/questions/46346486/angular-2-4-how-to-check-length-of-inputs-value-using-directive