Search code examples
angulareventsangular-ng-if

How to display the length of string in textfield using events in angular.?


I am doing a task where i need to display the length of the string entered into the textfield using Events. One more additional condition is if the string length is greater than 4 then only it will display the length which should be achieved by using ngIf.

Work Done by me till now In HTML

<div class="container">
    <input type="text" placeholder="Default Message" 
    [(ngModel)]="tname"
    (tname)="event('tname')">
    {{s}}
</div>

In .ts

tname:string;
k:number;
event(s:string){
this.k = s.length ;
 console.log(s);
}

Solution

  • You already bind tname using ngModel directive which is two-way binding. So just tname.length will solve your problem.

    Here is solution

    HTML

    <div class="container">
        <input type="text" placeholder="Default Message" 
        [(ngModel)]="tname"
        (tname)="event('tname')">
        {{s}}
     <span *ngIf="this.k > 4"> Length is {{this.k}}></span>
    </div>
    

    TS

    event(s:string){
      this.k = this.tname.length ;
        console.log(this.k); // displaying  length
    }
    

    Hope this help!