将startsWith用作自定义管道

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

实际上,我想使用*ngIf检查字符串是否以某些字符开头。

是否可以通过使用angular来做到这一点?我已经尝试过,但是出现错误

HTML

<app-breadcrumb  *ngIf="startsWith:url === '/register/'"></app-breadcrumb>

Component

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'startsWith'
})
export class UserComponent implements PipeTransform {
  transform(fullText: string, textMatch: string): boolean {
    return fullText.startsWith(textMatch);
  }
}
javascript html angular typescript
2个回答
2
投票

除了Eliseo所说的以外,我还想更正您对pipe的现有使用。

<div>{{ name | startsWith : 'Ang' }}</div>

<div *ngIf="( name | startsWith : 'Ang')"> Can see </div>

<div *ngIf="( name | startsWith : 'Test')"> Can't see </div>

看这个演示code here

OR

<app-breadcrumb  *ngIf="(url.startsWith('/register/'))"></app-breadcrumb>

不要使用pipe进行此类检查,主要是用于数据转换


0
投票

管道用于转换输入。作为有角度的文档状态

管道将数据作为输入并将其转换为所需的输出。

您可以简单地使用

<app-breadcrumb  *ngIf="url.startsWith('register')"></app-breadcrumb>

谢谢。

© www.soinside.com 2019 - 2024. All rights reserved.