简体   繁体   English

Angular 8 过滤器:保留文本区域输入的换行符

[英]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:我尝试使用 angular 8 制作过滤器,以在我的文本区域输入中保留文本换行符,文本输入将放置在图像上方:

<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 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 !我是 angular 的新手,我不确定 pipe 是否写得好! can some one help !有人可以帮忙!

Working example for Angular with Reactive forms , if you want to use template driven form , use instead of formControlName="message" ---> [(ngModel)]="message" Angular 与Reactive forms的工作示例,如果您想使用模板驱动的表单,请使用代替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;}

Working Demo工作演示

Try this one in pipe:在 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">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM