Deal with reactive form and tag adding

Viewed 37

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 class="tags">
        <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[]
}
2 Answers

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.

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 nested formGroup , in the nested formGroup you can add a formArray that containg the tag formGroup or formControl. then every time you click to the add button , we add the new tag value into the tag formArray.

let's make the update of your code :

1- update the formGroup and add the formArray

 this.searchForm = new FormGroup({
      'name': new FormControl(),
      'tag': new FormControl(),
      'tags': new FormArray([])
    })

2- add two method that allows us to add and get the list of tags

 getTags() {
    return this.searchForm.get("tags").value;
  }

  addTag(tagValue: string): void {
    const tagControl = new FormControl(tagValue)
    this.searchForm.get('tags').push(tagControl);
  }

3- finally we update the html code to get the list of tags and add the addTag action

<form [formGroup]="searchForm">
 Name : <input  formControlName="name">
  Tag : <input #tag formControlName="tag" placeholder="Enter a tag">
  <input type="button" value="add tag" (click)="addTag(tag.value)">
  <ul class="tags">
    <li *ngFor="let tag of getTags()">
      {{ tag }}
    </li>
  </ul>
</form>
<input type="button" (click)="onSearch()" value="search">

4- you will have something like this as a result

enter image description here

Related