[英]Loop through each character in a string with ngFor?
I have a string which I want to add certain styles to depending on the character.我有一个字符串,我想根据字符添加某些 styles 。 To do that, I need to loop through each character in the string.为此,我需要遍历字符串中的每个字符。
The data I'm getting from a third party api is returning a data set with data which starts with the keyed in term.我从第三方 api 获得的数据正在返回一个数据集,其中的数据以键入的术语开头。 So if a user types "far" into an input field, the api might return something like this:因此,如果用户在输入字段中键入“远”,api 可能会返回如下内容:
[
{ name: 'far' },
{ name: 'farsighted' },
{ name: 'farted'},
{ name: 'farmhouse'}
]
in this case the first object is an exact match to what the user typed in.在这种情况下,第一个 object 与用户输入的内容完全匹配。
Now, on the UI, I show the list of results from this API call.现在,在 UI 上,我显示了这个 API 调用的结果列表。
HTML may be like: HTML 可能类似于:
<ng-container *ngFor="let result of resultsFromAPI>
<span>{{result.name}}</span>
</ng-container>
But - what I want to do is loop through each character in the result.name span and bold the characters which are an exact match to the user inputted term.但是 - 我想要做的是遍历 result.name 范围中的每个字符,并将与用户输入的术语完全匹配的字符加粗。 I've tried a splitstring pipe, but that doesn't seem to be doing the trick, or maybe my html was wrong.我已经尝试过拆分字符串 pipe,但这似乎没有奏效,或者我的 html 是错误的。
<div>
<span *ngFor="let char of term.ticker | split term.ticker" class="symbol">
<span *ngFor="let num of char | split char">{{char}}</span>
</span>
</div>
My split pipe:我的拆分 pipe:
export class SplitStringPipe implements PipeTransform {
transform(value: any, args?: any): any {
console.log(value.split(''))
return value.split('');
}
}
I think the issue here is in the split pipe.我认为这里的问题在于拆分 pipe。
"hello world".split()
returns ["hello world"]
"hello world".split()
返回["hello world"]
"hello world".split('')
returns ["h","e","l","l","o"," ","w","o","r","l","d"]
"hello world".split('')
返回["h","e","l","l","o"," ","w","o","r","l","d"]
Make sure that you are splitting based on the empty string.确保基于空字符串进行拆分。
Update: It looks like your pipe is correct.更新:看起来您的 pipe 是正确的。
I'm not sure what comparisons you are trying to do with term.ticker
but hopefully something like this would work:我不确定您要与term.ticker
进行哪些比较,但希望这样的事情会起作用:
<ng-container *ngFor="let result of resultsFromAPI">
<ng-container *ngFor="let char of result.name | split">
<span [ngStyle]="{[insert conditional styles here]}">{{char}}</span>
</ng-container>
</ng-container>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.