Home > database >  Extract the comma separated values from a string and display on mat-chip
Extract the comma separated values from a string and display on mat-chip

Time:01-05

I have a string with list of courses chosen for example

courses_chosen = "AWS, Python, Java, Kotlin, Angular, typescript, Javascript";

Now I want to display on mat-chip I tried with following code

<mat-chip-list>
   <mat-chip *ngFor = "let courses of courses_chosen>
         {{courses}}
   </mat-chip>
</mat-chip-list>

But the data displayed on a single chip but I want to display each comma separated values into each chip. Please help

CodePudding user response:

You can use the function SPLIT to get each item separated by a comma.

courses_chosen = "AWS, Python, Java, Kotlin, Angular, typescript, Javascript";
const courses_chosen_list = courses_chosen.split(',');
// courses_chosen_list = ["AWS", "Python", ...., "Javascript"]

then:

<mat-chip-list>
  <mat-chip *ngFor = "let course of courses_chosen_list">
     {{ course }}
  </mat-chip>
</mat-chip-list>

CodePudding user response:

Hello have you tried this?

<mat-chip-list>
   <mat-chip *ngFor = "let courses of courses_chosen.split(',')">
         {{courses}}
   </mat-chip>
</mat-chip-list>

CodePudding user response:

if you have an empty variable string you want to remove

courses_chosen = "AWS, Python, Java, Kotlin, Angular, ,typescript, Javascript";

add map, trim and filter

const res = tags
  .split(',')
  .map((tag) => tag.trim())
  .filter((tag) => tag.length !== 0);
console.log(res);

result like :

[
  "AWS",
  "Python",
  "Java",
  "Kotlin",
  "Angular",
  "typescript",
  "Javascript"
]
  •  Tags:  
  • Related