Reputation: 25
I want to create a message. Whether it is irrelevant in the html or ts file, it is only important that if a field is empty, skip comma ?
<span> Personal data: {{ data.firstName }} , {{ data.lastName }} , {{ data.age }}
At some point firstName or lastName or age is empty and then the comma remains unnecessary? Example be:
Michael , , 21
or , , 21 ..
I want if no value , no print comma.
Upvotes: 0
Views: 1096
Reputation: 65
[data.firstName, data.lastName, data.age ].filter(v=>v).join(" , ")
Object.values(data).filter(v=>v).join(" , ")
Upvotes: 1
Reputation: 1121
Another clean solution:
Method:
calculateData(data: any) {
return Object.keys(data).map(i => data[i] ? data[i] + ', ' : '').join('').slice(0,-2);
}
And use like this:
<span> data: {{ calculateData(data) }}</span>
Upvotes: 1
Reputation: 8269
You can implement it like this instead:
Template
<span> Personal data: {{ getPersonalData(data) }}</span>
Component
@Component({...})
export class AppComponent {
...
getPersonalData({ firstName = '', lastName = '', age = null }) {
return `${firstName} ${lastName} ${age ? age : ''}`
.split(' ')
.filter(Boolean)
.join(', ');
}
}
Alternative Solution
As per Michael Geary's concern below if in case either firstName or lastName has 2 or more words
getPersonalData({ firstName = '', lastName = '', age = null }) {
return Object
.entries({ firstName, lastName, age })
.map(([, value]) => value)
.filter(Boolean)
.join(', ');
}
Have created a Stackblitz Demo for your reference containing all various scenarios when either firstName, lastName, or age is empty.
Upvotes: 1
Reputation: 1279
You need to write your own code for this: in ts file you can create the following function:
f(data): string {
let a: string[] = [];
if(data.firstname && data.firstname != "") a.push(data.firstname);
if(data.lastname && data.lastname != "") a.push(data.lastname);
if(data.age && data.age != "") a.push(data.age);
return a.join(" , ");
}
And later in the HTML side:
<span> Personal data: {{ f(data) }} </span>
Upvotes: 2