Home > Software engineering >  Deal with reactive form and tag adding
Deal with reactive form and tag adding

Time:08-15

I have a search component that includes searching by name and by tags for now. I've decided to use a form to validate and create a Search object with the form's value.

The problem is that I have to add a tag to a list each time the user press enter in the tag input but how can I do that in a form way?

<form [formGroup]="searchForm" (ngSubmit)="onSearch()">
    <input ... formControlName="name"...>
    <input ... placeholder="Enter a tag">
    <ul >
        <li *ngFor"...">
    </ul>
</form>

EDIT

I am using the form value like this:

this.searchEvent.emit(<Search>this.searchForm.value);

As you can see, only the tag input is attached to the form but not the list

export interface Search {
    name?: string
    tags: string[]
}

CodePudding user response:

as i see , you want to add the new added tag to the list when you tap enter. i advice you first to add a button click to add the tag to support tablet and mobile phones. so , to have the list of the added tags, you need to use enter image description here

CodePudding user response:

Catch keyboard events on the tag input (specifically key up), and if it's ENTER, add the tag to the list.

Two things to note:

  1. You need a button for adding tags as well, tablet and mobile users don't always have ENTER keys.
  2. If you have a button with type submit, it will also catch the ENTER key and try to submit the form.
  • Related