使用 startsWith 作为自定义管道

jav*_*ens 1 html javascript typescript angular

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

是否可以通过使用角度来做到这一点?我试过了,但出现错误

HTML

<app-breadcrumb  *ngIf="startsWith:url === '/register/'"></app-breadcrumb>
Run Code Online (Sandbox Code Playgroud)

成分

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

@Pipe({
  name: 'startsWith'
})
export class UserComponent implements PipeTransform {
  transform(fullText: string, textMatch: string): boolean {
    return fullText.startsWith(textMatch);
  }
}
Run Code Online (Sandbox Code Playgroud)

Sha*_*vek 5

除了 Eliseo 所说的之外,我还想纠正您现有的pipe.

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

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

<div *ngIf="( name | startsWith : 'Test')"> Can't see </div>
Run Code Online (Sandbox Code Playgroud)

此处查看此演示代码

或者

<app-breadcrumb  *ngIf="(url.startsWith('/register/'))"></app-breadcrumb>
Run Code Online (Sandbox Code Playgroud)

不要pipe用于此类检查,主要用于数据转换