Introduction
We can create chips in Angular using Material design very easily. There are lots of sample codes available in this context. I was thinking about creating the chips feature without using Material design so, that we can avoid the extra library and dependency of Material. I have achieved this goal with some simple steps and here, I am demonstrating the entire process.
Below is the screenshot of my working application.
To showcase the chips feature, we will create an Angular 8 application with default app component, and we will add two input boxes for capturing username and technical skills set of that user. After entering each skill set, user can hit enter key to create a skillset chip. We will use very simple logic for this. Though, this is a very simple demonstration, we have handled keypress events and curser focus to various HTML controls through “ViewChild” and “nativeElement.focus” method. We can see all these actions step by step.
Create a new Angular 8 application using CLI
If you have not installed Angular CLI, please install using npm command. (Please make sure, you could install latest node.js in your machine.)
npm i -g @angular/cli
After installing the CLI, we can create new Angular application using below command.
ng new AngularChips
After few minutes, entire node modules will be created successfully. Now we can add below packages to the project.
cd AngularChips (relocate to new project folder)
npm i bootstrap
npm i font-awesome
We must import both these libraries in styles.css file. So, that we can access these libraries globally in entire application, without further reference.
styles.css
- @import "~bootstrap/dist/css/bootstrap.css";
- @import "~font-awesome/css/font-awesome.css";
We are capturing the username and skills set in this application. Hence, we must create an interface for User data.
We can add required properties to this interface.
ng g i User
user.ts
- export interface User {
- userName: string;
- skillsSets: string[];
- }
We are using template driven forms to capture user data from screen. Hence, we must imports “FormsModule” in app.module.ts file.
app.module.ts
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
- import { FormsModule } from '@angular/forms';
-
- import { AppComponent } from './app.component';
-
- @NgModule({
- declarations: [
- AppComponent
- ],
- imports: [
- BrowserModule,
- FormsModule,
- ],
- providers: [],
- bootstrap: [AppComponent]
- })
- export class AppModule { }
We can add required html items in app component template file.
app.component.html
- <div style="margin: 10px;" class="row">
- <div class="col-md-6">
- <div class="row">
- <button class="btn btn-success mr-2" style="width:120px;" type="submit" (click)="newOrCancel()">
- New User
- </button>
- </div>
- <div class="form-group row mb-2">
- <label class="col-md-4 col-form-label" for="userName">User Name</label>
- <div class="col-md-8">
- <input class="form-control" type="text" id="userName" placeholder="User Name" [(ngModel)]="userName"
- [disabled]="!isInsert" autofocus (keydown.enter)="skillsSetFocus()" #userNameRef/>
- </div>
- </div>
- <div class="form-group row mb-2">
- <label class="col-md-4 col-form-label" for="skillsSet">Skills Sets</label>
- <div class="col-md-8">
- <input class="form-control" type="text" id="skillsSet" placeholder="Enter each Skills Set and hit 'Enter' Key."
- [(ngModel)]="skillsSet" (keydown.enter)="onSkillsSetKeydown()" #skillsSetRef/>
- </div>
- </div>
- <div class="row mb-2">
- <div class="col-md-4"></div>
- <div class="col-md-8">
- <div *ngFor="let skill of skills; let i = index" class="roundedcorner">
- {{skill}}
- <i class="fa fa-times-circle" style="font-size:24px;color:red;" (click)="dropSkill(i)"></i>
- </div>
- </div>
- </div>
- <div class="offset-md-4">
- <button class="btn btn-primary mr-2" style="width:80px;" type="submit" [disabled]="!isInsert || skills.length==0 || userName==null || userName==''" (click)="saveUser()">
- Save
- </button>
- <button class="btn btn-warning mr-2" style="width:80px;" type="submit" (click)="newOrCancel()">
- Cancel
- </button>
- </div>
- </div>
- <div class="col-md-3">
- <div class="card">
- <div class="card-header">
- Users List
- </div>
- <div class="card-body">
- <div *ngFor="let user of users">
- <a href="#" (click)="selectUser(user)">{{user.userName}}</a>
- </div>
- </div>
- </div>
- </div>
- </div>
We have used very simple logic to create chips for skills set. We will store these skills in a “skills” variable and using “ngFor” we have populated in div element.
- <div class="col-md-8">
- <div *ngFor="let skill of skills; let i = index" class="roundedcorner">
- {{skill}}
- <i class="fa fa-times-circle" style="font-size:24px;color:red;" (click)="dropSkill(i)"></i>
- </div>
- </div>
After saving the data, each user information (username and skills set array) will be added to another array variable “users” and populated in another div element in the right side of the application.
We can add business logic in the app component file.
app.component.ts
- import { Component, OnInit, ViewChild, ElementRef, HostListener } from '@angular/core';
- import { User } from './user';
-
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.css']
- })
- export class AppComponent implements OnInit {
- @ViewChild('userNameRef', { static: false }) userNameRefElement: ElementRef;
- @ViewChild('skillsSetRef', { static: false }) skillsSetRefElement: ElementRef;
-
- skillsSet: any;
- skills: string[] = [];
- users: User[] = [];
- userName: any;
- isInsert: boolean;
-
- onSkillsSetKeydown() {
- if (this.skillsSet == "" || this.skillsSet == null) return;
- this.skills.push(this.skillsSet);
- this.skillsSet = "";
- }
-
- dropSkill(index: any) {
- this.skills.splice(index, 1);
- }
-
- ngOnInit() {
- this.isInsert = true;
- }
-
- selectUser(user: User) {
- this.isInsert = false;
- this.userName = user.userName;
- this.skills = user.skillsSets;
- this.skillsSet = "";
- }
-
- newOrCancel() {
- this.isInsert = true;
- this.userName = "";
- this.skillsSet = "";
- this.skills = [];
- this.userNameRefElement.nativeElement.focus();
- }
-
- saveUser() {
- var user: User = {
- userName: "",
- skillsSets: []
- };
- user.userName = this.userName;
- user.skillsSets = this.skills;
- this.users.push(user);
- this.newOrCancel();
- }
-
- skillsSetFocus() {
- this.skillsSetRefElement.nativeElement.focus();
- }
-
- @HostListener('window:keydown', ['$event'])
- onKeyPress($event: KeyboardEvent) {
- if (($event.ctrlKey || $event.metaKey) && $event.keyCode == 83) {
- $event.preventDefault();
- if (this.skills.length > 0 && this.userName != null && this.userName != '' && this.isInsert == true) {
- this.saveUser();
- }
- }
-
- }
- }
We have added a method “onSkillsSetKeydown” to add skill to “skills” variable.
- onSkillsSetKeydown() {
- if (this.skillsSet == "" || this.skillsSet == null) return;
- this.skills.push(this.skillsSet);
- this.skillsSet = "";
- }
We have added two “ViewChild” variables to create references for two input elements username and skills set.
This ViewChild variables will be used to set cursor focus to respective elements in run time.
- skillsSetFocus() {
- this.skillsSetRefElement.nativeElement.focus();
- }
In addition to chips feature, we have created a “HostListener” to listen key actions. We can press “Ctrl + S” key combinations to save the user data. We have handled these actions in code.
- @HostListener('window:keydown', ['$event'])
- onKeyPress($event: KeyboardEvent) {
- if (($event.ctrlKey || $event.metaKey) && $event.keyCode == 83) {
- $event.preventDefault();
- if (this.skills.length > 0 && this.userName != null && this.userName != '' && this.isInsert == true) {
- this.saveUser();
- }
- }
- }
We must add a small style class to handle the chips behaviour in app component style file.
app.component.css
- .roundedcorner {
- margin: 5px;
- padding: 5px;
- float: left;
- border-radius: 25px;
- border: 2px solid #73AD21;
- }
We have completed entire coding. We can run the application now.
We can add multiple skills for a user and display as chips. We can add “n” number of users and their skills set and it will be added to the memory list. Please note, this will not persist after page refresh as we have stored it as in-memory.
Conclusion
In this post, we have created an Angular 8 application using CLI command and then we added an attractive chips feature with help of simple typescript and few HTML elements. We have also used HostListener to get key events and using that, we have saved the user data with simple “Ctrl + S” command. Hope, you have understood clearly about the chips feature in Angular without material design. Please feel free to give your comments and feedback.