Search code examples
javascriptangulartypescriptnested-forms

Angular 2 - Change nested form input value


I made a filter for my nested inputs, im using javascript to filter a link whenever paste event is fired.

function fixLink(foo){

            if (foo.includes('youtube') && (foo.includes('watch')) || foo.includes('vimeo') && !foo.includes('video') ) {
              foo = foo.includes('youtube') ? 'https://www.youtube.com/embed/' + foo.slice(foo.indexOf('=') + 1) : foo;
              foo = foo.includes('vimeo') ? 'https://player.vimeo.com/video/' + foo.slice(foo.indexOf('com/') + 4) : foo;
            }

            return foo;
          }

input.addEventListener('paste', () => {
            setTimeout(() => {
              input.text = fixLink(input.value);
              input.value = fixLink(input.value);
            }, 100)
          });

This is my HTML

@Component({
        selector: 'video-control',
        template: `<div class="form-group p-0 mb-2" [formGroup]="video">
        <div class="input-group group-social">
        <input [disabled]="onHold" class="form-control" formControlName="url" type="text" (focus)="setUrl($event.target)" placeholder="https://www.youtube.com/watch?v=IWfWqDhx65s">
        <button type="button" class="remove-photo-gallery btn btn-sm btn-danger" (click)="removed.emit(index)">
        <i class="fas fa-trash"></i>
        </button>
        </div>
        </div>`,
      })

It changes input value but when i save the value it comes as if the filter didn't work.

I can only get my filter to work if i add something else to the input like a space.


Solution

  • What I can deduce from your HTML is that you have a FormGroup called video and it has a FormControl called url. These are the edits I think you need to make.

    Update your input element to use the Angular (paste) event emitter:

    <input [disabled]="onHold" class="form-control" formControlName="url" type="text" (focus)="setUrl($event.target)" (paste)="onPaste($event)" placeholder="https://www.youtube.com/watch?v=IWfWqDhx65s">
    

    Then in your component have the following method:

    onPaste(event: ClipboardEvent) {
        const clipboardData = event.clipboardData || window.clipboardData;
        const fixedLink = this.fixLink(clipboardData.getData('text'));
        window.setTimout(() => this.video.get('url').value = fixedLink);
    }
    

    You would also need to move this fixLink function to be part of the component as well. If your hope is to have plain JS update the Angular FormGroup then you're using Angular wrong and I strongly advise against continuing along that path.