Как я могу передать неизменную форму по умолчанию после изменения одного элемента управления формы? - PullRequest
0 голосов
/ 13 июня 2019

У меня есть список предложений, вызванных из базы данных.Я создал кнопку рядом с каждым полем, в котором содержится информация о предложении, которая при нажатии отображает форму, позволяющую изменить все, что вы хотите о предложении.

Проблема в том, что если я оставлю элемент управления формы пустым, тоэто изменит реальное предложение, и я не хочу этого, поэтому что мне делать, чтобы, если поле формы пустое, оно не учитывалось.

Вот компонент HTML :

<div id="editOffer2" style="display: none">
  <div class="container">
    <div class="row">
      <div class="col-md-6 offset-md-3">
        <form [formGroup]="editofferForm" (ngSubmit)="editOffer()">
          <div class="form-group" style="margin-top: 30px;">
            <label style="font-weight: 600; margin-right: 50px; font-size: 1rem">Offer Name</label>
            <input type="text" formControlName="offername" class="form-control">
            <!-- <div *ngIf="submitted && d.offername.errors" class="invalid-feedback">
                <div *ngIf="d.offername.errors.required">Offer Name is required</div>
            </div> -->
          </div>
          <div class="form-group" style="margin-top: 30px;">
            <label style="font-weight: 600; margin-right: 50px; font-size: 1rem">Description</label>
            <textarea formControlName="description" class="form-control" cols="40" rows="9"></textarea>
            <!-- <div *ngIf="submitted && d.description.errors" class="invalid-feedback">
                <div *ngIf="d.description.errors.required">Description is required</div>
            </div> -->
          </div>
          <div class="form-group" style="margin-top: 30px;">
            <label style="font-weight: 600; margin-right: 50px; font-size: 1rem">Contact</label>
            <input type="text" formControlName="contact" class="form-control" />
            <!-- <div *ngIf="submitted && d.contact.errors" class="invalid-feedback">
                <div *ngIf="d.contact.errors.required">Contact is required</div>
            </div> -->
          </div>
          <div class="form-group" style="margin-top: 30px;">
            <label style="font-weight: 600; margin-right: 50px; font-size: 1rem">Location</label>
            <input type="text" formControlName="location" class="form-control"/>
            <!-- <div *ngIf="submitted && d.location.errors" class="invalid-feedback">
                <div *ngIf="d.location.errors.required">Location is required</div>
            </div> -->
          </div>
          <div class="form-group" style="margin-top: 30px;">
            <label style="font-weight: 600; margin-right: 50px; font-size: 1rem">Salary</label>
            <input type="text" formControlName="prix" class="form-control" />
            <!-- <div *ngIf="submitted && d.prix.errors" class="invalid-feedback">
                <div *ngIf="d.prix.errors.required">Price is required</div>
            </div> -->
          </div>
          <div class="form-group" style="margin-top: 30px;">
            <label style="font-weight: 600; margin-right: 50px; font-size: 1rem">Category:</label>
            <select formControlName="services" style="width: 150px">
              <option *ngFor="let s of allServices" [ngValue]="s">{{s.serviceName}}</option>
            </select>
          </div>
            <!-- <div class="form-group">
              <mat-select placeholder="Pick Category" formControlName="services" [ngClass]="{ 'is-invalid': submitted && d.services.errors }">
                <mat-option *ngFor="let s of services" [value]="s.serviceName">
                  {{s.viewValue}}
                </mat-option>
              </mat-select>
              <div *ngIf="submitted && d.services.errors" class="invalid-feedback">
                <div *ngIf="d.services.errors.required">You must choose a category</div>
              </div>
            </div> -->
          <div class="form-group">
            <button class="btn btn-primary" type="submit">Submit</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

Файл TS :

import { Component, OnInit, EventEmitter } from '@angular/core';
import { UserService } from '../user.service';
import { DomSanitizer } from '@angular/platform-browser';
import { HttpClient, HttpResponse, HttpEventType } from '@angular/common/http';
import { Observable } from 'rxjs';
import { UploadFileServiceService } from '../upload-file-service.service';
import { FormGroup, FormBuilder } from '@angular/forms';
import { Router } from '@angular/router';
import { MatSnackBar } from '@angular/material';

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

    loggedIn: boolean;
    loginUser: any = {};
    role: any;
    offers: any[] = [];
    myOffers: any[] = [];
    imgSrc: any;
    selectedOffer: any;
    progress: { percentage: number} = { percentage : 0};
    currentFileUpload: File;
    selectedFiles: FileList;
    editBioForm: FormGroup;
    infoForm: FormGroup;
    offerForm: FormGroup;
    editofferForm: FormGroup;
    allServices: any[] = [];

    constructor(private service: UserService,
                private sanitizer: DomSanitizer,
                private http: HttpClient,
                private uploadservice: UploadFileServiceService,
                private fb: FormBuilder,
                private router: Router,
                private snackbar: MatSnackBar) { }

    ngOnInit() {
        this.editofferForm = this.fb.group({
            offername: [''],
            description: [''],
            contact: [''],
            location: [''],
            prix: [''],
            services: ['']
        });
    }

    editOffer() {
        console.log('form: ', this.editofferForm.value);
        console.log('token: ', this.loginUser.token);
        this.service.editOffer(this.editofferForm.value, this.loginUser.token, this.selectedOffer.offerId).subscribe(res => {
            console.log('yeeeeeeet');
            document.getElementById('editOffer2').style.display = 'none';
            location.reload();
        }, err => {
            console.log(err);
        });
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...