我在[[HTML中具有下面的代码:已使用Angular材质使用以下形式创建文本框:
<form (ngSubmit)="onSubmit()" [formGroup]="myForm" #f="ngForm">
<mat-form-field appearance="outline" class="postField">
<textarea matInput placeholder="Say something.." name="postBody"
formControlName="postBody" type="text" [ngModel]="postBody | hashtag"
(ngModelChange)="postBody=$event" >
</textarea>
</mat-form-field>
<br/>
<button mat-raised-button color="primary" [disabled]="isDisabled"> Post </button>
</form>
[我正在尝试实现类似twitter / fb的标签功能,在此过程中,编写帖子并使用#something ...文本以及哈希值会突出显示为蓝色。尝试使用管道实施。以下是ts文件。
import { PipeTransform, Pipe } from '@angular/core'; @Pipe({ name: 'hashtag' }) export class HashtagPipe implements PipeTransform { constructor() {} transform(text: string){ let text1; if (text.indexOf('#') !== -1) { const str = text.replace(/#/g, '<span class="highlighted"></span>'); text1 = text; } else { text1 = text; } return text1; } }
这不起作用。需要进行哪些更改?
transform(text: string){
let text1;
if (text.indexOf('#') !== -1) {
text1 = text + ' ';
const matches = text1.match(/#(.*?) /g);
for(let i = 0; i < matches.length; i++){
text1 = text1.replace(matches[i], '<span class="highlighted">' + matches[i] + '</span>');
}
} else {
text1 = text;
}
return text1;
}
也请查看以下内容:https://stackblitz.com/edit/angular-iy46gj?file=src%2Fapp%2Fhashtag.pipe.ts