0

I currently have this:

<div *ngIf="name !== '@name1'>
  Show something
</div>

But I would like to change it to check if var name value starts with a specific character for example @.

How can I do this?

Felix Lemke
  • 6,189
  • 3
  • 40
  • 67
user13962846
  • 83
  • 2
  • 9
  • 1
    Does this answer your question? [Use ngIf checking if a string starts with certain character](https://stackoverflow.com/questions/51429248/use-ngif-checking-if-a-string-starts-with-certain-character) – Joseph Chotard Aug 17 '20 at 09:53

3 Answers3

3

Use startsWith method like this

<div *ngIf="name.startsWith('@')">
  Show something
</div>

And if you want to check if string doesn't start with '@' simply add '!' like *ngIf="!name.startsWith('@')"

Alexis
  • 1,685
  • 1
  • 12
  • 30
1

You can simply use indexOf method to get starting index of your character and if it's 0 it means it's true else false.

Like below.

<div *ngIf="name.indexOf('@name1') === 0">
   it's start with @name1
</div>

<div *ngIf="name.indexOf('@name1') !== 0">
  it's not start with @name1
</div>
Vivek Jain
  • 2,730
  • 6
  • 12
  • 27
1

you can just add this code inside the Component :

export class NameComponent implements OnInit {

public isNameContainAt = false;
public name = 'name';
constructor() { }

ngOnInit() {
if (this.name.startsWith('@') == true) {
  this.isNameContainAt = true;
}

}

}

And then in the template :

<div *ngIf="!isNameContainAt">

Show something

yanesof__
  • 144
  • 7