Search code examples
angulartypescriptangular-ngmodel

how to edit the data from "ngModel" before display in two way binding


    <textarea #hello class="form-control" name="Input" type="text" rows="10" cols="40" [(ngModel)]="answer">
    </textarea>
    
    <div class="message">
      {{ answer }}
    </div>
    transform(value: string): string {
        return value.replace(/\\n/g, '<br />');
      }
    answer = '';

My requirement is i need to get some data from user, store it in a variable, make some changes/replace a few things, preserve it's state (linebreaks, space) and then display it.

Can I intercept the data from ngModel before it is displayed and store it in a variable, make changes and then display it as normal ngModel

If this is not possible, appreciate any help in filling this requirement through any other method. Need some guidance


Solution

  • <textarea #hello class="form-control" name="Input" type="text" 
     rows="10" cols="40" [(ngModel)]="answer" (keyup) 
      ="onKeyUp($event)">
      </textarea>
    
      <div class="message">
     {{ formated }}
      </div>
    

    typescript

    onKeyUp(event: any)
    {
    This.formated = event.target.value.replace(/\\n/g, '<br />');
     }
     answer = '';
     formated: string