JSONオブジェクトで文章を受け取るコンポーネントがあります。各文には、さまざまな色に関連付けられた単語の配列が含まれています。その上完全な文のうち選択された単語にhtmlタグを追加する角度2
[{
"message": "Attention! The user already exists.",
"words": [
{"word": "user", "color": "#ffddcc"},
{"word": "Attention!", "color": "#ff99cc"},
{"word": "exists", "color": "#cddcef"}
]
},
{"message": "Hey! There are no users",
"words": [{"word": "users","color": "#ffddcc"},{"word": "Hey!","color": "#ff99cc"},{"word": "are","color": "#cddcef"}]},
{"message": "This is a are recipe","words": [{"word": "are","color": "#ffddcc"},{"word": "recipe","color": "#cddcef"}]}
]
そして:
後は、次のように私が取得しています
export class ExampleComponent implements OnInit, OnDestroy {
ngOnInit() {this._getChats(userId);}
private _getData(userId: string) {
this.dataSub = this.api
.getDataList$()
.subscribe(
res => {
this.data = res.result.data;
},
error => {
console.log(error);
});
}
}
データがあるコンポーネントの抜粋です。
<div *ngFor="let dt of data">{{dt.message | formatData:dt.words}}</div>
を次のように は、今私は現在、私のhtmlでこれらの文章を示すのです私の問題は、私は
<div><span style="color:#ff99cc">Attention!</span> The <span style="color:#ffddcc">user</span> already <span style="color:#cddcef">exists</span>.
以下のようにそれぞれのカラーコードのspanタグを配列に言及したすべての単語を置き換えたいということです
文字列を識別して置き換えるカスタムパイプを作成しようとしました。しかし、私はここで立ち往生しています。
以下は私が書いたカスタムパイプです。
export class FormatDataPipe implements PipeTransform {
transform(value: string, args: any) {
if(args.length === 0) {
return value;
}
for(let i =0; i < args.length; i++) {
if(value.includes(args[i].word)) {
const subVal = `<span style='color:'"` + args[i].color + `"'>` + args[i].token + `</span>`;
value.replace(args[i].token, subVal);
}
}
}
}
ありがとうございました。
はあなたがしようとしたカスタムパイプのコードを追加することができますし、あなたが得ているエラーは何ですか? –
私は使用しているパイプを追加しました。 – 1ns4n3