網站搜尋

javascript - 使用 startsWith 作為自訂管道


其實我想使用 *ngIf 檢查一個字串是否以某個字符開頭。

使用 Angular 可以做到這個嗎?我嘗試過但出現錯誤

HTML

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

元件

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

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

答案#1

在補充Eliseo的說法之外,我也想更正你現有對pipe的使用。

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

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

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

看看這個示範程式碼

或

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

不要使用 pipe 來進行這類檢查,它主要是用於資料轉換

答案#2

管道的目的是轉換輸入。正如 Angular 文件中所述

管道將數據作為輸入並將其轉換為所需的輸出。

你可以直接使用

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

謝謝。