Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 8 filter : preserve line breaks on text area input

I trying to make a filter with angular 8 to preserve text line break on my text area input, the text input will be placed above an image :

<div class="form-group col-10">
          <span class="badge badge-theme mb-3">Message personnalisé</span>
          <textarea class="form-control" id="exampleFormControlTextarea1" formControlName="personalizedMessage"
            rows="6"></textarea>

        </div>
<div class="col-6" style="margin-top: 35px;">
      <div class="row">
        <div class="col-12 card-container">
          <img src={{displayedImage}} alt="">
          <div class="message">
            <p ng-bind-html="personalizedMessage | linebreaks">{{giftCardForm.controls['personalizedMessage'].value}}</p>
          </div>
        </div>
      </div>
    </div>

pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'linebreaks'
})
export class LinebreaksPipe implements PipeTransform {

  transform(text: any): any {
    return text.replace(/\n/g, "<br>");
  }

}

I'm new with angular and I'm not sure if the pipe is written good ! can some one help !

like image 886
sahnoun Avatar asked Dec 18 '22 15:12

sahnoun


2 Answers

Working example for Angular with Reactive forms, if you want to use template driven form , use instead of formControlName="message" ---> [(ngModel)]="message"

  1. Have a textarea where you put the input

Example

 <textarea placeholder="Message" formControlName="message" rows="3"></textarea>
  1. Where you display it

<div class="message" [innerHTML]="message">

  1. Style the container with

.message { white-space: pre-wrap;}

like image 63
Sorin Veștemean Avatar answered Jan 05 '23 17:01

Sorin Veștemean


Working Demo

Try this one in pipe:

 export class LinebreaksPipe implements PipeTransform {

      transform(value: string): string {
        return value.replace(/\\n/g, '<br />');
      }
    }

In template file:

<p [innerHTML]="profileForm.get('personalizedMessage').value | linebreaks">
like image 40
Saurabh Yadav Avatar answered Jan 05 '23 17:01

Saurabh Yadav