在Angular 8中,你可以使用ngModel
指令和textarea
元素来实现在文本区域输入中保留换行符的功能。
首先,在你的组件中,定义一个变量来存储文本区域的内容,例如text
:
export class MyComponent {
text: string;
}
然后,在模板中使用textarea
元素和ngModel
指令来绑定文本区域的内容:
接下来,创建一个自定义管道来处理文本区域的内容,保留换行符。在你的组件文件中,创建一个名为NewlineFilterPipe
的管道,并实现transform
方法:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'newlineFilter'
})
export class NewlineFilterPipe implements PipeTransform {
transform(value: string): string {
return value.replace(/\n/g, '
');
}
}
在模板中,使用管道来应用过滤器,并显示保留换行符的文本:
最后,将自定义管道添加到你的模块的providers
数组中:
import { NewlineFilterPipe } from './newline-filter.pipe';
@NgModule({
declarations: [
// other declarations
NewlineFilterPipe
],
// other module properties
})
export class MyModule { }
现在,当你在文本区域中输入内容时,换行符将被保留,并在页面上正确显示。