1

How do I reset an angular input element to pristine with no data? My model is an object.

In my current version (Stackblitz example) the data is reset once but the view model is not properly updated the second time around.

v0v1v2

I've encountered this answer on stackoverflow but the primary answer relies on using a wrapper form element.

Raven
  • 1,453
  • 3
  • 18
  • 29

1 Answers1

1

I updated your code with my answer.

You can see the full code here: https://stackblitz.com/edit/angular-gdajaw

Only thing I changed is (and I strongly recommend it) instead of timeout, I use ChangeDetectorRef to wait for angular change detection to run. After change detection you can select the added input to focus.

Here is the changed AppComponent:

import { Component, Renderer2, ChangeDetectorRef } from '@angular/core';
import { Note } from './note.model';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  public notes: Note[] = [];
  public newNote = new Note();

  constructor(
    protected renderer: Renderer2,
    private cRef: ChangeDetectorRef
  ) { }

  ngOnInit() {
    this.notes.push(new Note({ content: 'foo' }));
    this.notes.push(new Note({ content: 'bar' }));
  }

  newLine(note: string) {

  // Switch it up
  this.notes.push(new Note(this.newNote));

  // Select our original element
  // setTimeout(() => this.renderer.selectRootElement('#note'+(this.notes.length-1)).focus(), 0);

  // use ChangeDetectorRef detectChanges method to wait for angular to go through change detection
  this.cRef.detectChanges();
  // after change detection you can select the added input to focus
  this.renderer.selectRootElement('#note' + (this.notes.length - 1)).focus()

  // Reset the new line
  //this.newNote = new Note();
  this.newNote = new Note({content: null});
  }
}
bodorgergely
  • 558
  • 1
  • 3
  • 12
  • Thanks! Functionally that's exactly what I want. I do still wonder if it's possible to reset an input element without form wrapper to it's pristine state. – Raven Jul 06 '18 at 23:38