使用 Angular 7 中的数据反应表单初始化 [英] React form initialization with data in Angular 7

查看:35
本文介绍了使用 Angular 7 中的数据反应表单初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有编辑反应形式.在 ngOnInit() 我试图用服务器数据初始化表单.首先我会调用api,然后设置数据.但是发生的事情是在数组从 api 接收数据之前,表单被初始化.因此,我收到错误

<块引用>

无法读取未定义的属性get"

标记:

 
<h2>用户</h2><div class="form-controls"><mat-form-field><input matInput placeholder="用户名" type="email" formControlName="username"><mat-error *ngIf="已提交&& formControl.username.errors"><mat-error *ngIf="formControl.username.errors.required || formControl.username.hasError('email')">* 有效的电子邮件必需</mat-error></mat-error></mat-form-field>

<div class="form-controls"><mat-form-field><input matInput placeholder="名字" type="text" formControlName="firstname"><mat-error *ngIf="已提交&& formControl.firstname.errors"><mat-error *ngIf="formControl.firstname.errors.required">* 需要名字</mat-error></mat-error></mat-form-field>

<div class="button-section"><button mat-flat-button color="primary" (click)="closeDailog()" id="cancel"><i class="material-icons">clear</i>Cancel</button>;<button mat-flat-button color="primary" type="submit" id="create"><i class="material-icons">done</i>编辑</button>

</表单>

代码:component.ts:

 ngOnInit(){this.UserServiceObj.getUserDetailOnID(this.userId).subscribe((res) => {控制台日志(res);//this.initializeDetail();this.userDetail = res;});this.userForm = this.formBuilder.group({用户名:[this.userDetail['username'], [Validators.required, Validators.email]],名字:[this.userDetail['firstname'], Validators.required])};}

解决方案

我没有运行代码但是:subscribe 是异步的,它将在您的服务返回时执行.设置订阅后,您立即尝试从 this.userDetails 设置属性,在该时间点可以 undefined

您可以尝试这样的操作或将您的回复映射到一个 Observable,您可以使用 ngIf 和异步管道在模板中订阅它 https://angular.io/tutorial/toh-pt6

async ngOnInit() {这个.userDetail = await this.UserServiceObj.getUserDetailOnID(this.userId).toPromisse();this.userForm = this.formBuilder.group({用户名:[this.userDetail['username'], [Validators.required, Validators.email]],名字:[this.userDetail['firstname'], Validators.required])};}

关于其他部分,您可以在下面找到一份工作表格,它应该可以帮助您修复您的问题

<p>请输入您的用户名和密码.</p><form [formGroup]="loginForm" (ngSubmit)="login()"><div class="row form-group"><div class="col"><input type="text" class="form-control" placeholder="用户名" formControlName="用户名">

<div class="row form-group"><div class="col"><input type="password" class="form-control" placeholder="密码" formControlName="密码">

<div class="text-center"><button type="button" class="btn btn-outline-secondary mr-3" (click)="close()">取消</button><button type="submit" class="btn btn-outline-primary">登录</button>

</表单>

@Component({选择器:'应用程序登录',templateUrl: './login.component.html',styleUrls: ['./login.component.scss'],})导出类 LoginComponent {登录表单 = 新表单组({用户名:new FormControl(''),密码:new FormControl(''),});构造函数(私有用户服务:用户服务,私人模式:NgbActiveModal){}登录() {this.userService.login();}关闭() {this.modal.close();}}

I have edit reactive-form. In ngOnInit() I'm trying to initialize the form with server data. First I will call api and then the data is set. But what is happening is that before array receives data from api, the form get initialized. Because of that I am getting an error

Cannot read property 'get' of undefined

Markup:

 <form [formGroup]="userForm" (ngSubmit)="onSubmit()">
       <h2>Users</h2>
       <div class="form-controls">
         <mat-form-field>
           <input matInput placeholder="User name" type="email" formControlName="username">
           <mat-error *ngIf="submitted && formControl.username.errors">
           <mat-error *ngIf="formControl.username.errors.required || formControl.username.hasError('email')"> * Valid
            Email
            required</mat-error>

          </mat-error>
         </mat-form-field>
       </div>
       <div class="form-controls">
         <mat-form-field>
           <input matInput placeholder="First name" type="text" formControlName="firstname">
           <mat-error *ngIf="submitted && formControl.firstname.errors">
             <mat-error *ngIf="formControl.firstname.errors.required"> * First Name required</mat-error>

           </mat-error>
         </mat-form-field>

       </div>
       <div class="button-section">
               <button mat-flat-button color="primary" (click)="closeDailog()" id="cancel"><i class="material-icons">clear</i>Cancel</button>
               <button mat-flat-button color="primary" type="submit" id="create"><i class="material-icons">done</i>Edit</button>

       </div>
 </form>

Code: component.ts:

 ngOnInit(){
  this.UserServiceObj.getUserDetailOnID(this.userId).subscribe((res) => {
  console.log(res);
  // this.initializeDetail();
  this.userDetail = res;

  });

  this.userForm = this.formBuilder.group({
  username: [this.userDetail['username'], [Validators.required, Validators.email]],
  firstname: [this.userDetail['firstname'], Validators.required])};
}

解决方案

I did not run the code but: subscribe is asyc and it will execute when your service returns. Immediately after setting up a subscription you try to set properties from this.userDetails that at the point of time can be undefined

You can try something like this or map your reply to an Observable which you can than subscribe to in your template with ngIf and async pipe https://angular.io/tutorial/toh-pt6

async ngOnInit() {
  this. userDetail  = await this.UserServiceObj.getUserDetailOnID(this.userId).toPromisse();

  this.userForm = this.formBuilder.group({
  username: [this.userDetail['username'], [Validators.required, Validators.email]],
  firstname: [this.userDetail['firstname'], Validators.required])};

}

Regarding the other part you can find a working form below it should help you to fix yours

<div class="p-3">
  <p>Please enter your username and password.</p>
  <form [formGroup]="loginForm" (ngSubmit)="login()">
    <div class="row form-group">
      <div class="col">
        <input type="text" class="form-control" placeholder="Username" formControlName="username">
      </div>
    </div>
    <div class="row form-group">
      <div class="col">
        <input type="password" class="form-control" placeholder="Password" formControlName="password">
      </div>
    </div>
    <div class="text-center">
      <button type="button" class="btn btn-outline-secondary mr-3" (click)="close()">Cancel</button>
      <button type="submit" class="btn btn-outline-primary">Login</button>
    </div>
  </form>
</div>

@Component({
  selector:    'app-login',
  templateUrl: './login.component.html',
  styleUrls:   ['./login.component.scss'],
})
export class LoginComponent {

  loginForm = new FormGroup({
    username: new FormControl(''),
    password: new FormControl(''),
  });

  constructor(private userService: UserService,
              private modal: NgbActiveModal) {
  }

  login() {
    this.userService.login();
  }

  close() {
    this.modal.close();
  }
}

这篇关于使用 Angular 7 中的数据反应表单初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆