比较Angular 4中的子串

问题描述 投票:2回答:1

我想只显示链接以“https://”开头的项目。我想将子字符串与* ngIf中的特定字符串进行比较:

<div *ngIf="item.link | slice:0:8 == 'https://'">
    <div class="title">
      <a class="title-pointer" href="{{item.link}}">{{item.title}}</a>
    </div>
</div>

我从/ @ angular / core导入了Pipe和PipeTransform,切片似乎工作:

{{item.link | slice:0:8}}

输出:https://

如果我将* sting与* ngIf中的子串进行比较,为什么它不起作用?我应该修改什么?

angular
1个回答
1
投票

虽然@DanielWStrimpel在评论中的解决方案可能有效,但整个应用程序中的这种可重用性大约为零。

我建议创建一个通用的应用程序范围的服务,它可以为您处理此过程:

export class AppService {
  // match 'https://'
  public isHttps(link: string){
    return link.indexOf("https://") >= 0;
  }
  // match a provided string
  public match(link: string, match: string){
    return link.indexOf(match) >= 0;
  }
}

这样,您现在也可以根据需要匹配任何提供的字符串,例如子域,或者即使您想要从站点X排除https://链接

所以你的*ngIf将是:

<div *ngIf="appService.isHttps(item.link)">

或者如果你想匹配https://链接并从stackoverflow.com中排除网站:

<div *ngIf="appService.isHttps(item.link) && !appService.match('stackoverflow.com')">

这也比分割字符串和执行此评估两次更快,性能更明智,就像使用pipe一样。

以下是服务的一个工作示例:https://stackblitz.com/edit/angular-aegndv


Note: Name the service something more appropriate of course.
© www.soinside.com 2019 - 2024. All rights reserved.