Inline Editing Numbers with Angular 6

Are you looking for a component that can make input numbers great again👏

How it looks like

Let’s get started. For reach this behavior we will create 1 directive and component in Angular 2+. Working DEMO at stackblitz

edit-input.component.ts

@Component({selector: 'app-edit-input',templateUrl: './edit-input.component.html',styleUrls: ['./edit-input.component.scss'],})export class EditInputComponent implements OnInit {@Input() data: number;@Output() focusOut: EventEmitter<number> = new EventEmitter<number>();currency = '$';editMode = false;constructor() {}ngOnInit() {}onFocusOut() {this.focusOut.emit(this.data);}}

Logic is pretty simple, we have input data for form an output event that emitted than user click enter or removes focus from the element.

edit-input.component.scss

.cell {border: 2px solid transparent;padding: 11px 20px;width: 100%;height: 100%;&:hover {cursor: pointer;border: 2px dashed $lightGray;}}.cellInput {border: 2px solid transparent;padding: 11px 20px;width: 100%;height: 100%;}

edit-input.component.html

<input *ngIf='editMode' (focusout)="onFocusOut()" (keydown.enter)='$event.target.blur()' [(ngModel)]='data' class='cellInput'appAutofocus type='number' (keydown.enter)='$event.target.blur()' (focusout)="editMode=false">

Here is two div that replace each other depending on a flag editMode . However, you probably notice the appAutoFocus directive, let's take a look at how it realized:

autofocus.directive.ts

@Directive({selector: '[appAutofocus]',})export class AutofocusDirective implements OnInit {constructor(private elementRef: ElementRef) {}ngOnInit(): void {this.elementRef.nativeElement.focus();}}

Basically that it, now you can use this component everywhere in your code.

Example:

Component and DEMO available here:

https://stackblitz.com/edit/angular-inline-edit

I am writing about my entrepreneurial journey as a full-stack developer and co-founder at Sensivo.eu. https://skob.io/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store