是否可以在Angular5中使用ViewChild提交表单?

时间:2018-07-09 11:48:02

标签: angular

是否可以使用Angular5代码的ViewChild提交表单?怎么样?
我尝试过,但是没有成功

HTML:

 <form #form="ngForm" (submit)="submitForm(form)" novalidate>
  <input required type="text" #codeRequest="ngModel" [(ngModel)]="requestModel.codeRequest" id="codeRequest" name="codeRequest"/>
 </form>

 <button (click)="func()"> </button>

TypeScript:

@ViewChild('form') form: ElementRef;
  constructor(){}

  func(){
    this.formStep2.nativeElement.submit();
  }

  submitForm(form: NgForm) {
    ... 
  }

我的问题在哪里?

3 个答案:

答案 0 :(得分:1)

要在表单外提交带有按钮(类型=提交)的表单,您可以执行以下操作

定义模型:

export interface Student {
  id: number;
  name: string;
}

在app.component.ts中:

  public model: Student;

  @ViewChild('form', { read: NgForm }) form: any;

  ngOnInit(): void {
    this.setDefaultValueForModel();
  }

  saveForm($event: Event) {
    $event.preventDefault();

    if (this.form.valid) {
       console.log(this.form.value);
       alert('valid');
     } else {
     alert('invalid');
   }
}

setDefaultValueForModel() {
  this.model = {
    id: 0,
    name: ''
  };

最后是您的app.component.html

   <form #form="ngForm" novalidate id="ngForm" (submit)="saveForm($event)">
    <div class="form-group">
      <label>Name</label>
      <input type="text" required name="name" [(ngModel)]="model.name" #name="ngModel">
      <p *ngIf="name.invalid && name.touched">
        Family is required.
      </p>
    </div>
  </form>

  <div>
    <button type="submit" form="ngForm" [disabled]="!form.form.valid">
      Save
    </button>
  </div>

DEMO

答案 1 :(得分:0)

您想通过单击按钮提交表单,按钮位于表单之外。

以下将是您的视图/ html:

<div >
  <button (click)="onSubmit()">Submit from outside</button>

  <form [formGroup]="fooForm" (ngSubmit)="onNgSubmit()">
    <label>Label One:</label>
    <input formControlName = "fieldOne">

    <label>Label Two:</label>
    <input formControlName = "fieldTwo">

  </form>
</div>

现在在控制器中, 当您单击按钮时,调用与ngSubmit事件绑定的方法。

export class YourComponent  {
  public fooForm: FormGroup;

  ngOnInit(){
    this.fooForm = new FormGroup({
      'fieldOne':new FormControl('value-one'),
      'fieldTwo':new FormControl('value-two')
    });
  }

  public onSubmit(){
    console.log("submitting from out side the form");
    this.onNgSubmit();
  }

  public onNgSubmit(){
    console.log(this.fooForm.value);
  }
}

stackblitz

答案 2 :(得分:-1)

将按钮添加为表单内的简单方法

如果这不是您要按下按钮的方式,则必须采取其他方法。

您必须利用反应形式,并在您的代码中

func(){ 
    if(this.ngForm.valid){ 
        const formValues = this.ngForm.value;
        this.http.post(url,formValues).subscribe(x => { ... })
    }
}