如何以反应形式从.ts文件访问输入字段的值

时间:2019-02-06 07:18:50

标签: angular

在简单的 constructor(private router: Router, private route: ActivatedRoute) { let url = this.router.url; const index = this.router.url.lastIndexOf(this.route.pathFromRoot[this.route.pathFromRoot.length - 1].routeConfig.path.split('/')[0]); url = this.router.url.substring(0, index) + this.route.pathFromRoot[this.route.pathFromRoot.length - 1].routeConfig.path; console.log(this.router.url) // /iauth/iauthedit/1853 console.log(url) // /iauth/iauthedit/:itemCode let yourRequiredUrl = url.split(':')[0] // /iauth/iauthedit/ } 中,我曾经在函数的参数中传递NgForm的值,它曾经起作用,但不适用于反应形式。 #myForm="ngForm"e.controls.first_name.value不会获取ts文件中输入字段的值。我想获取这些值,以便可以在e.controls方法中传递它。

registerUser

ts文件

<form method="post" [formGroup]="registerForm" (ngSubmit)="onSubmit()">
              <div id="tab-2" class="log-tab-content">
                <div class="login-form">

                  <div class="login-left">
                    <input type="text" name="first_name" placeholder="First Name *"/>
                    <div class="clearfix"></div>
                    <input type="text" name="email" placeholder="Email *"/>
                    <div class="clearfix"></div>
                    <input type="text" name="password" placeholder="Password *"/>
                    <div class="clearfix"></div>
                  <button type="submit" class="log-button log-button1">Register now</button>
                </div>
              </div>
            </form>

1 个答案:

答案 0 :(得分:0)

您错过了html中每个输入的formControlName。您应该为每个输入添加formControlName

在ngOnInit中以表格形式添加所有变量

  ngOnInit() {
    this.registerForm = this.formBuilder.group({
      first_name: ['', Validators.required],
      last_name:['', Validators.required],
      email: ['', Validators.required],
      c_email: ['', Validators.required],
      password:['', Validators.required],
      c_password:['', Validators.required],
      birth_date: ['', Validators.required],
      phone: ['', Validators.required],
      timezone: ['']
    })
}




onSubmit() {
const user = this.registerForm.value;
        }

像下面一样在您的html中添加formControlName

 <form method="post" [formGroup]="registerForm" (ngSubmit)="onSubmit()">
              <div id="tab-2" class="log-tab-content">
                <div class="login-form">

                  <div class="login-left">
                    <input type="text" formControlName="first_name" name="first_name" placeholder="First Name *"/>
                    <div class="clearfix"></div>
                    <input type="text" name="email" formControlName="email" placeholder="Email *"/>
                    <div class="clearfix"></div>
                    <input type="text" formControlName="password" name="password" placeholder="Password *"/>
                    <div class="clearfix"></div>
                  <button type="submit" class="log-button log-button1">Register now</button>
                </div>
              </div>
            </form>