【问题标题】:Applying styles to string characters with ngClass function使用 ngClass 函数将样式应用于字符串字符
【发布时间】:2020-12-18 02:14:57
【问题描述】:

我正在尝试编写一个在 [ngClass] 中使用的函数,以将 CSS 类应用到 较大字符串中的某些字符。这些字符是从第 3 方 API 返回的。

假设返回的数据是这样的:

data = [
 { name: 'Johnny', description: "Johnny ate an apple."},
 { name: "Bobby", description: "Bobby hates apples."}
]

我的 HTML 将遍历数据数组中的所有对象并将它们打印到 UI。但是,我需要搜索每个对象上的每个描述属性,并找出是否存在完全匹配并将样式应用于该单词。

因此,我需要逐个字符地比较两个字符串。

假设类是“text-italics”。哪种情况下的 CSS 应该是这样的:

.text-italics {
  text-transform: italics !important;
}

我的字符串是“约翰尼吃了一个苹果”。来自对象一的描述属性。

但我只希望“苹果”斜体。不是“ate”中的“a”或“an”中的“a”。

对象二也是如此。 “apples”中的“apple”应该是斜体。不是“讨厌”中的“a”。

<ng-container *ngFor="let char of item.description | splitString ">
   <span [ngClass]="{'text-italics' : applyItalics(item.descripton, b)}">
     {{char}}
  </span>
</ng-container>

我正在尝试编写一个将在 [ngClass] 中使用的函数。我想我会用.split('') 将字符串分解成字符数组,然后循环遍历 HTML 中的每个字符?

我正在使用这样的函数,但是一旦我知道用户搜索的术语在 termToCheckAgainst 中,我需要将样式应用于每个完全匹配的字符:

applyItalics(nameOfData: string, termUserSeachedFor: string): boolean {
    nameOfData = nameOfData.toUpperCase();
    termUserSeachedFor = termUserSeachedFor.toUpperCase();
    return nameOfData.includes(termUserSeachedFor);
}

【问题讨论】:

  • 你错过了结束 '}' => [ngClass]="{'text-teal' : applyItalics(termToCheck)}"
  • 是的,但该代码只是一个示例。那是行不通的,因为当我只想要“apple”风格化时,它会将样式应用于“ate”中的“a”。
  • 你可以在组件中创建html内容,然后在模板上渲染?
  • 另外,字符串是动态的还是总是一样的?
  • 它是动态的。内容实际上是从值的 API 返回的数组。我需要遍历数组中每个对象的特定属性,并且它们对于这个字符串属性都有不同的内容,并检查是否有匹配项。

标签: javascript angular typescript


【解决方案1】:

您不需要为此设置两个单独的函数,只需包含管道中的所有内容:

@Pipe({
  name: 'wrapItalic'
})
export class WrapItalic {
  transform(content, word) {
    const splits = content.split(' ');
    let result = '';
    splits.forEach(next => {
        word === next ? result += ` <i>${next}</i> ` : result += ` ${next}`;
    });
    return result.trim();
  }
}

还有你的 HTML:

  Test <span [outerHTML]="'Jonny ate an Apple' | wrapItalic: 'Apple'"></span>

这可能更快,因为你只做一次工作(循环)

【讨论】:

  • 这很容易实现,我什至没有考虑自定义管道。谢谢!
【解决方案2】:

如果您想通过字符作为完整搜索词的一部分来设置字符样式,则需要在描述中传递字符的索引,例如 let char of outerItem.description | splitString; let i = index; 并使用一些算法来检查字符是否属于搜索词。由于我们正在规范化为大写,因此我使用小写字母“a”。

    //our root app component
import { Component, NgModule, VERSION } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

 import { splitStringPipe }          from './split-string.pipe';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <dl>
      <dt>Term</dt>
      <dd><input [(ngModel)]="b" /></dd>
      </dl>

      <ng-container *ngFor="let outerItem of data">
    <ng-container *ngFor="let char of outerItem.description | splitString; let i = index;">
      <span [ngClass]="{'text-italics' : applyItalics(outerItem.description, i, b)}">
        {{char}}
      </span>
    </ng-container>
    </ng-container>
    </div>
  `,
})
export class App {
  data: object[];
  b: string;
  constructor() {
    this.b = "term";
    this.data = [
      { name: 'Johnny', description: "Johnny ate an apple."},
      { name: "Bobby", description: "Bobby hates apples."}
    ];
  };

  applyItalics(desc,i,b) {

     if (desc) {
      let normalDesc = desc.toUpperCase();
      let normalTerm = b.toUpperCase();
      let tTerm = normalDesc.replace(normalTerm,Array(normalTerm.length+1).join("a"));
      return tTerm[i] === 'a';
     }
     return false;
  }
}

@NgModule({
  imports: [BrowserModule, FormsModule],
  exports: [splitStringPipe],
  declarations: [splitStringPipe,App],
  bootstrap: [App],
})
export class AppModule {}

这是 Plunker https://embed.plnkr.co/plunk/pXhbQbZhDnM1jNZ7 上的完整示例

【讨论】:

    猜你喜欢
    • 2018-10-15
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 2014-05-02
    • 2014-06-15
    • 1970-01-01
    • 2011-01-15
    • 2016-08-03
    相关资源
    最近更新 更多