Search code examples
angularstringangular-ng-if

Angular check string pattern on `Template`


I am trying to add a condition to my *ngIf where it will display only if the string ends with .txt in my template.

I've tried this but it's not working:

<div *ngIf="myfilename.endsWith('.txt')">...</div>

I know the above does not work, so my question is:

How can I do this so I only display .txt filenames?


Solution

  • It's better to check it in your component.ts for example like this:

    app.component.ts

    import { Component, OnInit  } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent impelemnts OnInit  {
      myfilename: string;
      isTxt: boolean = false;
    
      ngOnInit() {
        this.isTxt = this.myfilename.endsWith(".txt")
      }
    }
    

    app.component.html

    <div *ngIf="isTxt">...</div>