【问题标题】:Check if a string starts with certain character using ngIf and display it使用 ngIf 检查字符串是否以某个字符开头并显示
【发布时间】:2020-07-10 03:54:36
【问题描述】:

我是这里的新手,我有问题要解决。请帮忙,提前谢谢。

我通常像这样在屏幕上显示数据,而且每次都能正常工作。

<h3> Kod Bar : {{ article.barcode_no }} </h3>

但现在我想检查使用 *ngIf 如果 article.barcode_no 以某个字符开头,我希望在显示它之前先将其删除。

<h3 *ngIf=" article.article.indexOf(article.barcode_no) === 'S' ? (article.barcode_no).substr(1) : none "> Kod Bar    : {{ article.barcode_no }} </h3>

但我不断收到错误

错误类型错误:无法读取未定义的属性“indexOf”

我也尝试使用 Pipe 但无法正常工作。请帮忙。谢谢。

 <h3 *ngIf=" (article.barcode_no | startsWith : 'S') ? (article.barcode_no).substr(1) : none "> Kod Bar    : {{ article.barcode_no }} </h3>

.

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

@Pipe({
    name: 'startsWith'
})

export class AccessProviders implements PipeTransform {

  transform(fullText: string, textMatch: string) : boolean {
      return fullText.startsWith(textMatch);
  }
}

[谢谢你们的回复。我感谢所有的答案! ]

【问题讨论】:

  • 使用str.chatAt(0) == 'YourChar' ? true : false;
  • 试试@NajamUsSaqib 的回答很简单
  • 我这样使用它 "

    Kod Bar : {{ article.barcode_no.chatAt(0) == 'S' ? article.barcode_no.substring(1): article.barcode_no }}

    ”并得到错误“ERROR TypeError: _v.context.$implicit.barcode_no.chatAt is not a function”

标签: angular ionic-framework pipe angular-ng-if


【解决方案1】:

你可以试试这个。

<h3 *ngIf="article.barcode_no.indexOf('S',0) == 0 "> Kod Bar    : {{ article.barcode_no.substring(1) }} </h3>

Stackblitz demo

【讨论】:

  • 您的代码有效,谢谢!但是现在如何从条形码中删除第一个字符?我这样写但什么也没做 "

    Kod Bar : {{ article.barcode_no }}

    "
  • 更新了答案和 stackblitz 链接。请尝试一下。
【解决方案2】:

首先,您会收到该错误,因为在评估时文章仍未设置。为了避免它从模板中出现,您可以使用问号语法来检查当时是否可以安全地访问该属性:

 *ngIf=" article?.article.indexOf(article.barcode_no)

您还确定它的 'article.article' 吗?因为在管道上你使用了另一个值,所以如果它不起作用,那么原因就不一样了

【讨论】:

    【解决方案3】:

    尝试像下面这样更新您的管道

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'startWith'
    })
    export class StartWithPipe implements PipeTransform {
    
      transform(value: any, args?: any): any {
        if(value && typeof(value) === 'string'){
          return value[0] === args;
        }
        return false;
      }
    
    }
    

    【讨论】:

    • 我收到错误“错误错误:未捕获(在承诺中):错误:模板解析错误:找不到管道'startsWith'”
    • 我分享的代码中有一个类型——startsWith——名称下的拼写不同:startWith,----所以只需更新名称就可以了
    【解决方案4】:

    你可以简单地通过这个存档。

    {{str.charAt(0) == 'YourChar' ? srt.substring(1): str}};

    【讨论】:

    • 我得到“ERROR TypeError: _v.context.$implicit.barcode_no.chatAt is not a function”。
    • 我错了,它应该是charAt。我编辑了答案..
    猜你喜欢
    • 2018-12-27
    • 1970-01-01
    • 2011-05-04
    • 2023-01-01
    • 2012-02-09
    • 2011-01-30
    • 2012-02-06
    • 1970-01-01
    相关资源
    最近更新 更多