2

Проект: https://github.com/mihinov/crm-angular
Компонент с которым проблема: ссылка

Есть такая форма c текстом и загрузкой файла:

введите сюда описание изображения

Я для тега form указал: <form (ngSubmit)="onSubmit()"></form>.
Кнопка сохранить изменения имеет input[type="submit"]
При клике на загрузить изображение, который является простым <button type="file"> происходит dispatchEvent у input[type="file"]
Непонятно почему срабатывает onSubmit при клике на загрузить изображение, почему он срабатывает?
Даже если отключить dispatchEvent, то всё равно почему-то срабатывает onSubmit

categories-form.component.html:

<div class="page-title">
  <h4>
      <a routerLink="/categories">Категории</a>
      <i class="material-icons">keyboard_arrow_right</i>
      {{ isNew ? 'Добавить' : 'Редактировать' }} категорию
  </h4>
  <span>
      <button class="btn btn-small red">
        <i class="material-icons">delete</i>
      </button>
    </span>
</div>

<div class="row">
  <form
    class="col s12 l6"
    [formGroup]="form"
    (ngSubmit)="onSubmit()"
  >
      <div class="input-field">
          <input
            id="name"
            type="text"
            formControlName="name"
            [ngClass]="{'invalid': form.get('name').invalid && form.get('name').touched}"
          >
          <label
            for="name"

          >Название</label>
          <span
            class="helper-text red-text"
            *ngIf="form.get('name').invalid && form.get('name').touched"
          >
            <span
              *ngIf="form.get('name').errors['required']"
            >
              Имя категории не может быть пустым
            </span>
          </span>
      </div>

      <div>
          <input
            type="file"
            class="dn"
            (change)="onFileUpload($event)"
            #input
          >
          <button
            (click)="triggerClick()"
            [disabled]="form.disabled"
            type="file"
            class="waves-effect waves-light btn orange lighten-2 mb2"
          >
              <i class="material-icons left">backup</i>
              Загрузить изображение
          </button>
      </div>

      <div>
          <button
            type="submit"
            [disabled]="form.invalid || form.disabled"
            class="waves-effect waves-light btn"
          >
              Сохранить изменения
          </button>
      </div>
  </form>

  <div class="col s12 l4 center">
      <img
        class="responsive-img h200"
        [src]="imagePreview"
        *ngIf="imagePreview"
      >
  </div>
</div>


<app-positions-forms></app-positions-forms>

categories-form.component.ts:

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { CategoriesService } from '../../shared/services/categories.service';
import { switchMap } from 'rxjs/operators';
import { of, Observable } from 'rxjs';
import { MaterialService } from '../../shared/services/material.service';
import { Category } from '../../shared/interfaces';

@Component({
  selector: 'app-categories-form',
  templateUrl: './categories-form.component.html',
  styleUrls: ['./categories-form.component.scss']
})
export class CategoriesFormComponent implements OnInit {

  @ViewChild('input') inputRef: ElementRef;

  isNew = true;
  image: File;
  imagePreview: string | ArrayBuffer = '';
  form: FormGroup;
  category: Category;

  constructor(private route: ActivatedRoute,
              private categoriesService: CategoriesService) { }

  ngOnInit(): void {
    this.form = new FormGroup({
      name: new FormControl(null, Validators.required)
    });

    this.form.disable();

    this.route.params
      .pipe(
        switchMap(
          (params: Params) => {
            if (params.id) {
              this.isNew = false;
              return this.categoriesService.getById(params.id);
            } else {
              return of(null);
            }
          }
        )
      )
      .subscribe(
        (category: Category) => {
          if (category) {
            this.category = category;
            this.form.patchValue({
              name: category.name
            });
            this.imagePreview = category.imageSrc;
            MaterialService.updateTextInputs();
          }

          this.form.enable();
        },
        err => MaterialService.toast(err.error.message)
      );
  }

  triggerClick(): void {
    this.inputRef.nativeElement.click();
  }

  onFileUpload(event: Event): void {
    const target = event.target as HTMLInputElement;
    const file = target.files[0];
    this.image = file;

    const reader = new FileReader();
    reader.readAsDataURL(file);

    reader.addEventListener('load', () => {
      this.imagePreview = reader.result;
    });
  }

  onSubmit(): void {
    let obs$: Observable<Category>;
    this.form.disable();

    if (this.isNew) {
      obs$ = this.categoriesService.create(this.form.value.name, this.image);
    } else {
      obs$ = this.categoriesService.update(this.category._id, this.form.value.name, this.image);
    }

    obs$.subscribe(
      (category: Category) => {
        console.log('Произошёл onSubmit');
        this.category = category;
        MaterialService.toast('Изменения сохранения');
        this.form.enable();
      },
      err => {
        MaterialService.toast(err.error.message);
        this.form.enable();
      }
    );
  }

}

1 ответ 1

2

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button

<button type="file">

Такого типа у кнопки нет, так что кнопка ведет себя как кнопка без типа, что по умолчанию значит type="submit". Поставьте:

<button type="button">

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.