Получение ошибки проверки после успешной отправки формы - PullRequest
0 голосов
/ 09 октября 2019

Я использую угловой 8 с угловым материалом 7. Я использую реактивную форму для создания и отправки форм. После отправки формы я программно перезагружаю форму и отмечаю ее как нетронутую. Но после каждой отправки я вижу все триггеры валидации и другие документы по

export class RegisterUserComponent implements OnInit{

  createUserForm: FormGroup;
  allRolesList: Array<UserRole>;
  assignedRoles: Array<UserRole>[];
  assignedRolesChanged = new Subject<Array<UserRole>>();
  newUser: GetUserResponse;

  constructor(private roleService: RoleService, private userService: UsersService) {
    this.roleService.allRolesListChanged.subscribe((res: Array<UserRole>)=>{
      this.allRolesList = res;
    });

    this.userService.newUserCreated.subscribe((res: GetUserResponse)=>{
      this.newUser = res;
      this.createUserForm.reset(true);
      this.createUserForm.markAsUntouched({onlySelf: true});
    });
   }

  async ngOnInit() {
    this.roleService.getAllRoles();

    this.initForm();
  }

  initForm(){
    this.createUserForm = new FormGroup({
      loginId: new FormControl(null, [Validators.required, Validators.email]),
      firstName: new FormControl(null, Validators.required),
      lastName: new FormControl(null, Validators.required),
      userRoles: new FormControl(null)
    });
  }
  onSubmit(){
    let data = this.createUserForm.value;
    console.log(data);
     let req: UserRequest = {
       loginId: data.loginId ? data.loginId.trim() : undefined, 
       firstName:data.firstName ? data.firstName.trim() : undefined, 
       lastName:data.lastName ? data.lastName.trim() : undefined, 
       assignedRoles: {userRoles:data.userRoles}
      };
     console.log(req);

    this.userService.registerNewUser(req);
  }

}

Шаблон HTML для for очень прост:

<div class="large-box mat-elevation-z4">
    <form id="simple-form-input" class="search-container" [formGroup]="createUserForm" (ngSubmit)="onSubmit()">
        <table>
            <tbody>
                <tr>
                    <td>
                </tr>
            </tbody>
        </table>
        <table cellspacing="0" cellpadding="5">
            <tbody>
                <tr>
                    <td>
                        <mat-form-field>
                            <mat-label>Login ID</mat-label>
                            <input matInput formControlName="loginId" type="text" name="loginId" placeholder="Login ID">
                        </mat-form-field>
                    </td>
                </tr>
                <tr>
                    <td>
                        <mat-form-field>
                            <mat-label>First Name</mat-label>
                            <input matInput formControlName="firstName" type="text" name="firstName"
                                placeholder="First Name">
                        </mat-form-field>
                    </td>
                </tr>
                <tr>
                    <td>
                        <mat-form-field>
                            <mat-label>Last Name</mat-label>
                            <input matInput formControlName="lastName" type="text" name="lastName"
                                placeholder="Last Name">
                        </mat-form-field>
                    </td>
                </tr>
                <tr>
                    <td>
                        <mat-form-field>
                            <mat-label>Access Privileges</mat-label>
                            <mat-select formControlName="userRoles" name="userRoles" multiple>
                                <mat-option *ngFor="let userRole of allRolesList" [value]="userRole">
                                    {{userRole.name}}
                                </mat-option>
                            </mat-select>
                        </mat-form-field>
                    </td>
                </tr>
                <tr>
                    <td>
                        <button [disabled]="!createUserForm.valid" type="submit" color="primary" mat-raised-button>Submit</button>
                    </td>
                </tr>

            </tbody>
        </table>
    </form>
</div>

1 Ответ

1 голос
/ 10 октября 2019

Недостаточно установить элементы управления на нетронутые, необходимо устранить ошибки в элементах управления, возникающие при сбросе из-за Validators.required:

this.createUserForm.reset();
Object.keys(this.createUserForm.controls).forEach(
  key => this.createUserForm.controls[key].setErrors(null)
);
this.createUserForm.markAsUntouched({onlySelf: true});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...