Reputation: 83
I am using this in Angular .html component
<div *ngIf="mystring.endsWith('.txt')">Content Here</div>
where is will only show the div only if mystring ends with .txt.
This works, but my question is...
How can I have multiple options here without having to use ||
(or) ?
Upvotes: 0
Views: 2049
Reputation: 2396
There are effectively four things you can do to achieve the functionality you want.
Create a pipe. Pipes will only fire when the mystring
variable changes, so it saves processing power.
html
<div *ngIf="mystring | checkExtension">Content Here</div>
pipe
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({name: 'checkExtension'})
export class CustomDatePipe implements PipeTransform {
transform(value) {
if (!value) {
return false;
}
return value.endsWith('.txt') || value.endsWith(...);
}
option is what Rafi said with a function call to the typescript. This is valid, but is generally bad practice because it will fire on every digest cycle, effectively wasting computation power, and slow down your application
html
<div *ngIf="showString()">Content Here</div>
typescript
showString() {
return this.mystring.endsWith('.txt') || this.mystring.endsWith(...);
}
is to just put it in the html, but that does make the file larger which you are trying to avoid. plus it fires the .endsWith()
every digest cycle which is wasted processing power.
<div *ngIf="mystring.endsWith('.txt') || mystring.endsWith('.pdf')">Content Here</div>
EDIT
Do as davidr suggests and add a new variable. This is a little less computationally intensive than using a pipe, but then you have to track when your mystring
changes. If your variable only changes on page load, I would suggest using davidr's answer. If you constantly changing your mystring
I would go the pipe route.
Upvotes: 1
Reputation: 1805
I would sugest you to put this kind of logic in the ts file, not in the template:
in the ts file:
public show: boolean;
ngOnInit() {
this.show = mystring.endsWith('.txt') || mystring.endsWith('.pdf');
}
And in your template:
<div *ngIf="show">Content Here</div>
Upvotes: 1
Reputation: 6422
I would suggest of using a getter as demonstrated below:
get show(): boolean {
return this.options.some(x => this.mystring.endWith(x))
}
<div *ngIf="show">Content Here</div>
Upvotes: 1