Отправить форму с угловым в файл Json - PullRequest
0 голосов
/ 25 сентября 2019

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

Я застрял с этого утра.

У меня уже есть способ удалитьно пропустите метод создания

это мой HTML

<div class="manage-content">
  <div class="title">
    <mat-icon class="user-icon">how_to_reg</mat-icon>
    <h3>Create a user</h3>
  </div>
      <form [formGroup]="form" (ngSubmit)="onSubmit()">
        Value : {{form.value | json}}
        <div class="form">
        <div class="leftSide">
        <mat-form-field class="full-width-input" appearance="outline">
          <input id="firstName" matInput placeholder="First name" formControlName="f_name" #f_name>
          <mat-error *ngIf="isFieldInvalid('f_name')">
            The first name you've entered is malformed.
          </mat-error>
        </mat-form-field>
        <mat-form-field class="full-width-input" appearance="outline">
          <input id="middleName" matInput placeholder="Middle name" formControlName="m_name" #m_name>
          <mat-error *ngIf="isFieldInvalid('m_name')">
            The middle name you've entered is malformed.
          </mat-error>
        </mat-form-field>
        <mat-form-field class="full-width-input" appearance="outline">
          <input id="lastName" matInput placeholder="Last name" formControlName="l_name" #l_name>
          <mat-error *ngIf="isFieldInvalid('l_name')">
            The last name you've entered is malformed.
          </mat-error>
        </mat-form-field>
        <mat-form-field class="full-width-input" appearance="outline">
          <input id="email" matInput placeholder="Email" formControlName="email" #email>
          <mat-error *ngIf="isFieldInvalid('email')">
            The email you've entered is malformed.
          </mat-error>
        </mat-form-field>
        <mat-form-field class="full-width-input" appearance="outline">
          <div class="visibility">
        <input id="password" matInput type="password" placeholder="Password" formControlName="password">
            <mat-icon class="eye" *ngIf="isPasswordVisible" (click)=showPassword()>visibility</mat-icon>
            <mat-icon class="eyeClosed" *ngIf="!isPasswordVisible" (click)="showPassword()">visibility_off</mat-icon>
          </div>
                  <mat-error *ngIf="isFieldInvalid('password')">
                    The password you've entered is malformed.
                  </mat-error>
      </mat-form-field>
        </div>
        <div class="cta-btn">
          <button mat-raised-button class="createUserBtn" color="primary" type="submit" (click)="onSubmit()">Create user</button>
          <button mat-raised-button class="createUserBtn" color="warn" type="submit" (click)="click()">Cancel</button>
        </div>
      </form>
</div>

, и это мой файл TS, это только часть моего метода (в процессе)

 onSubmit() {
      if (this.form.valid) {
        //TODO implement method to post data to API
        this.dialogRef.close(this.form.value);
        this.formSubmitAttempt = true;
        const Toast = Swal.mixin({
          toast: true,
          position: 'top-end',
          showConfirmButton: false,
          timer: 3000
        })
        Toast.fire({
          type: 'success',
          title: 'User created'
        })
      }

Спасибомного за вашу помощь

Ответы [ 2 ]

0 голосов
/ 26 сентября 2019

Свяжите свой элемент управления формой с помощью [(ngModel)] с объектом, который вы объявляете в своем ts.В методе onSubmit () делайте все, что нужно с этим объектом (отправьте запрос, вставьте в db ...).

0 голосов
/ 26 сентября 2019

enter image description here я предлагаю не использовать onSubmit, вместо этого используйте кнопку, связанную с такой функцией

`submitForm() {
    dataToPost = this.form.value;
     // data is the responce data from the backend when a  user created successfully
     // data shall be the created user only the backend knows this info
     this.hhtpClient.post(this.url, dataToPost).subscribe( data => { 
     this.form.get('m_name').setValue(data.m_name);
     this.form.get('l_name').setValue(data.l_name);
     this.form.get('email.).setValue(data.email);
     // add all controls you want to update after http response
    }
}`

enter code here `

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...