首页 > 解决方案 > 如何使用角度从html中的数组中提取前两个字符?

问题描述

我有一个 api 数组对象返回值如下:

apival = [{lang: "English",code: "en-ca"}, {lang: "French",code: "fr-ca"}]

我将这个数组与 ngfor 一起使用来显示 html 中的语言。我需要指定一个条件来应用一些逻辑。为此,我需要一个管道或其他东西,它可以在运行时从代码中提取前两个字符。

我知道如何在打字稿中拆分它。但是,我需要它在 HTML 中。在我的 TS 中:

currentlang = "en"

在我的 HTML 中:

<div*ngfor="let x of apival">
<div*ngIf="x.code == currentlang"></div>
</div>

在上面的 html 代码中,我需要一种从代码中提取前两个字符的方法。知道我该怎么做吗?

我不想使用 TS,我可以在 html 中使用管道或一些逻辑

标签: angular

解决方案


是的,使用Pipe它是正确的方法。尝试这个:

@Pipe({ name: "code" })
export class LangCodePipe implements PipeTransform {
  transform(value: any[], filter?: string): any {
    return value
      .map(lang => {
        return {
          ...lang,
          short: lang.code.split("-")[0]
        };
      })
      .filter(lang => {
        return filter ? filter == lang.short : true;
      });
  }
}

它将包含您需要的逻辑,并使过滤器成为可选的,Pipe返回实际对象以及短代码。

现在您需要做的就是:在模块中声明管道并在模板中使用它。

<!--currentLang is optional param-->
<div *ngFor="let x of apival | code: currentlang">
  {{x | json}}
</div>
<!-- you can also do this -->
<div *ngFor="let x of apival | code">
  {{x | json}}
</div>

完整的例子在这里


推荐阅读