Inline Editing Numbers with Angular 6

Alex Skobe
2 min readDec 8, 2018

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

import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';@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

$lightGray: #c8c8c8;.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

<div *ngIf='!editMode' (click)='editMode=true' class='cell'>{{currency}} {{ data | number:'':'en' }}</div><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

import { Directive, ElementRef, OnInit } from '@angular/core';@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:

<app-edit-input [data]='cost' (focusOut)='saveCost($event)'></app-edit-input>

Component and DEMO available here:

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

--

--

Alex Skobe

Software entrepreneur. Helping your digital business to build and grow. https://skobe.co