Search code examples
angularangular-formsangular9

Angular 9 Form submit options


I have a form that adds an item. I have two buttons, one to submit the form, adding the item and navigating back to the list of items and a second one to submit the form, clear it and remain on page to enter a new item again.

My thinking is to id the buttons in the html, and in my onAddItem() logic after the new item is dealt with have an if statement to either form.resetForm(); or router.navigate(['item-list-page']);

but i've had no luck implementing this line of thinking.

my code currently looks like:

html:

<div class="side-form">
  <h1>{{title}}</h1>
  <div class="form-container">
    <form (ngSubmit)="onAddItem(f)" #f="ngForm">
      <div class="form-group">
        <label for="y">Y</label>
        <input type="text" name="y" ngModel class="form-control" required />
      </div>
      <div class="form-group">
        <label for="x">X</label>
        <input type="text" name="x" ngModel class="form-control" required />
      </div>
      <div class="form-group">
        <button class="btn btn-primary">  
          Create
        </button>
        <button class="btn btn-outline-primary">
          Create and add another 
        </button>
      </div>
    </form>
    <button class="btn btn-outline-primary" routerLink="/x">
      Cancel
    </button>
  </div>
</div>

and my relevant controller.ts

export class ItemNewComponent implements OnInit {
  title: string;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private itemService: ItemService
  ) {}

  ngOnInit(): void {
    this.title = 'Add Item';
  }

  onAddItem(form: NgForm) {
    const value = form.value;
    const newItem = new Item(
      value.y,
      value.x,
    );
    this.itemService.addItem(newItem);
    this.router.navigate(['item']);
  }
}

I tried a couple of different options including separating the logic to two different functions and assigning click listeners to the buttons to fire off the relevant functions but no luck there either.

Thanks in advance


Solution

  • NOT use (ngSubmit)="onAddItem(f)" use, for each button (click)="onAddItem(f) and (click)="onAddItem(f,true). The button with ype="submit" was the defect button -if you key ENTER, make the action of this button-

     <div class="form-group">
        <button type="button" (click)="onAddItem(f) class="btn btn-primary">  
          Create
        </button>
        <button type="submit" (click)="onAddItem(f,true) class="btn btn-outline-primary">
          Create and add another 
        </button>
      </div>
    
    onAddItem(form: NgForm,goOn:boolean=false) {
       ....common actions...
       if (goOn)
       {
         ..your code..
       }
       else
       {
         ..your code..
       }