尝试将此Angular 7表单提交到我的打字稿上。 ngForm和[(ngModel)]

时间:2019-03-26 05:47:32

标签: javascript node.js angular forms typescript

我试图使用onSubmit()函数来传递此简单的表单信息,但是在执行它时,它会抱怨启动时未定义。我会弄乱一些语法吗?

<form class="gf-formbox" name="credentials" (ngSubmit)="onSubmit(f)" #f="ngForm" >
  <div class="form-group">
    <label for="gf-email">Email address</label>
    <input type="email" class="form-control" id="gf-email" placeholder="Enter email" [(ngModel)]="model.email" #email="ngModel" required>
    <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
  </div>
  <div class="form-group">
    <label for="gf-pass">Password</label>
    <input type="password" class="form-control" id="gf-pass" placeholder="Password" [(ngModel)]="model.password" #password="ngModel" required>
  </div>
  <div class="form-check">
    <input type="checkbox" class="form-check-input" id="exampleCheck1">
    <label class="form-check-label" for="exampleCheck1">Check me out</label>
  </div>
  <button type="submit" class="btn btn-primary" [disabled]="f.pristine">Submit</button>
</form>

2 个答案:

答案 0 :(得分:0)

您将必须在组件中声明变量,然后访问提交表单时的输入。这是一个演示如何实现的示例。 https://stackblitz.com/edit/angular-vwumm4enter代码在这里

在您的组件上:

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  private email: string;
  private password: string;

  onSubmit(f){
    console.log(this.email);
    console.log(this.password)
  }
}

在模板上:

<form class="gf-formbox" name="credentials" (ngSubmit)="onSubmit(f)" #f="ngForm">
  <div class="form-group">
    <label for="gf-email">Email address</label>
    <input type="email" class="form-control" id="gf-email" placeholder="Enter email" name="email" [(ngModel)]="email" required>
    <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
  </div>
  <div class="form-group">
    <label for="gf-pass">Password</label>
    <input type="password" class="form-control" id="gf-pass" placeholder="Password" name="password" [(ngModel)]="password" required>
  </div>
  <div class="form-check">
    <input type="checkbox" class="form-check-input" id="exampleCheck1">
    <label class="form-check-label" for="exampleCheck1">Check me out</label>
  </div>
  <button type="submit" class="btn btn-primary" [disabled]="f.pristine">Submit</button>
</form>

答案 1 :(得分:0)

获取表单信息Angular有两种表单方法-

您可以根据需要选择任何一个。希望它会有所帮助:)