将数据从HTML页面传递到打字稿文件

时间:2019-11-11 12:32:37

标签: html angular

我有一个用于表单的ngForm。我尝试将数据传递到.ts文件,但无法在控制台上打印它们。

这是我的代码:

<div class="column" style="padding: 7.5%">
<form #instituteForm="ngForm" (ngSubmit)="instituteLogin(instituteForm)">
    <div class="form-group">
        <label> Full Name </label>
        <input 
            type="text" 
            ng-maxlength="10" 
            hint="Full Name" 
            name="patient" 
            id="name" 
            class="form-control"
            [(ngModel)]="institute.patient">
        <label> Phone Number </label>
        <input 
            type="number" 
            hint="phone" 
            name="phoneno" 
            id="phone" 
            maxlength="10" 
            minlength="10" 
            class="form-control" 
            [(ngModel)]="institute.phoneno">
        <label> Aadhar Number </label>
        <input 
            type="number" 
            hint="aadhar" 
            id="aadhar" 
            name="aadhar" 
            maxlength="16" 
            minlength="16"
            class="form-control" 
            [(ngModel)]="institute.aadhar">
        <br><br>
    </div>
    <button id="signup" class="btn btn-primary" type="submit">Signup</button>
</form>
</div>

institute = {
    patient: '',
    phoneno: '',
    aadhar: '' 
};

instituteLogin(instForm: NgForm) {
    console.log("Entered new patient");
    console.log(instForm.value);
}

3 个答案:

答案 0 :(得分:2)

您尚未在 app.module.ts 中添加FormsModule。

import { FormsModule }   from '@angular/forms';

@NgModule({
    imports: [ 
        // Other imports  
        FormsModule 
    ]
})

工作演示:https://stackblitz.com/edit/angular-ybbamr

答案 1 :(得分:1)

在这种情况下,应该是这样的:

instituteLogin(): void{
    console.log("Entered new patient");

    console.log(this.institute);
   }

答案 2 :(得分:1)

好吧,我认为您应该使用FormControlName而不是ngModel。

html:

<div class="column" style="padding: 7.5%" >
   <form [formGroup]="institute" #instituteForm (ngSubmit)="instituteLogin()">
      <div class="form-group">
     <label> Full Name </label>
     <input type="text" ng-maxlength="10" hint="Full Name"   id="name"  class="form- 
      control" formControlName="patient">
       <label> Phone Number </label>
     <input type="number" hint="phone"  id="phone" maxlength="10" minlength="10"  
     class="form-control" formControlName="phoneno">

      <label> Aadhar Number </label>
       <input type="number" hint="aadhar" id="aadhar"  maxlength="16"  minlength="16" 
       class="form-control" formControlName="aadhar">
         <br><br>
      <button id="signup" class="btn btn-primary"  
      routerLink="../../home/dashboard">Signup</button>
      </div> </form>
     </div>

ts:

institute:FormGroup; 

instituteLogin(){
console.log("Entered new patient");

console.log(this.institute.value);


 }
constructor(private formBuilder:FormBuilder) { }
ngOnInit() {
this.institute =this.formBuilder.group( {
  patient: new FormControl(),
  phoneno:new FormControl(),
  aadhar:new FormControl()
});

}