I am trying to show array's object key comma separated, But I am getting extra comma(,) in starting.
getSeperatedByCommaName(): string {
let finalName = '';
this.options.Ids.forEach((value) => {
finalName = finalName + ',' + value.Name;
})
return finalName;
}
Am I doing something wrong? Or is there any way to display directly comma separated on html without writing above function?
Thanks in advance
Use join method:
let commaSeparatedNames = this.options.Ids.map(itm => itm.Name).join(',');
Normal way: Demo
get seperatedByCommaName(): string {
return this.options.Ids.map(value => value.Name).join(",");
}
In template:
<p>{{ seperatedByCommaName }}</p>
Another way Using pipe : Demo
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'join'
})
export class JoinPipe implements PipeTransform {
transform(input: Array<any>, sep = ', '): string {
return input.map(value => value.Name).join(sep);
}
}
Don't forget to declare JoinPipe in module like:
@NgModule({
imports: [],
declarations: [
JoinPipe
],
exports: [
JoinPipe // if to be made available outside modules
]
})
In Template
<p> {{ options.Ids | join }} </p>