Search code examples
angular2-formsangular4-forms

To take input element value's length in angular 2/4 form


In my angualr 2 template form, I've input field designed in a way like on focus, label animates on top of the input element and on focus-out label comes down back to the input element.similar like this one : [codepen]

My problem is the label comes down even when control has values which should be handled in code. I don't know how to take the length of the input element to check in my component to keep the label on top.

HTML :

<form #queryForm="ngForm" (ngSubmit)="Search(queryForm.value)">
<div class="form-input">
    <div>
        <input type="text" class="animate-label"
        (focusout)="onLeave(queryForm.value)" name="process" ngModel [ngClass]="{'ontop':hasValue}">
        <label>Process</label>
    </div>

Component :

export class FormTemplate{
hasValue:boolean;

onLeave(form:any){ //is this the right way to get the value back to component??
    console.log(form)
    if(form.process.length>0) //syntax??
    {
        this.hasValue=true;
    }
}}

When the element has value, i'll add up the ngClass #hasValue to keep label on top


Solution

  • This is what you want:

    <input type="text" class="animate-label"
        (focusout)="onLeave(queryForm.value)" name="process" [(ngModel)]="process" [ngClass]="{'ontop': process?.length}">
        <label>Process</label>
    

    Then you can remove onLeave and hasValue altogether.

    The problem is that you provided an empty ngModel which won't do anything.

    I don't know how your model looks but you might want to bind process to an object like [(ngModel)]="someObject.process" instead.