重置Angular 2中的内部表单控件

时间:2017-08-14 11:20:55

标签: angular typescript

我有一个表单控件loanTerm,它有另外两个内部表单控件年和月,我试图通过

重置它
this.form.control['years'].reset(); 

不幸的是它没有用,因为当我访问this.form.control的属性时,唯一可用的对象是loanTerm。

<df-years-months-question ng-reflect-_model="[object Object]" ng-reflect-minimum-period="48" ng-reflect-maximum-period="474" ng-reflect-question-label="Loan term" ng-reflect-name="loanTerm" id="loanTerm" class="ng-untouched ng-pristine ng-invalid"><div class="form-inline ng-untouched ng-pristine ng-valid" ng-reflect-form="[object Object]">
  <!--bindings={
  "ng-reflect-ng-if": "false"
}-->
  <div class="input-group col-xs-5 col-sm-3">
    <input class="form-control ng-untouched ng-pristine ng-valid" formcontrolname="years" type="number" ng-reflect-name="years" min="48" max="474">
    <span class="input-group-addon">years</span>

  <div class="input-group col-xs-5 col-sm-3">
    <input class="form-control ng-untouched ng-pristine ng-valid" formcontrolname="months" max="11" min="0" type="number" ng-reflect-name="months">
    <span class="input-group-addon">months</span>
  </div>
</div>
</df-years-months-question>  
  </div>

我已经尝试过以下方法:遗憾的是没有工作

  • this.form.control['loanTerm'].reset();
  • this.form.get('loanTerm').get('years').reset();

1 个答案:

答案 0 :(得分:0)

您只能重置整个表单而不是单个输入框而是尝试  在你的ts

    export class HeroDetailComponent4 {
  form: FormGroup;


  constructor(private fb: FormBuilder) {
    this.createForm();
  }

  createForm() {
    this.form= this.fb.group({
     "years":"",
     "months":""
    });
  }
}

并在你的HTML中

 <form [formGroup]="form" novalidate>
     <div >

              <div >
                <input formControlName="years" type="number" >
                <span class="input-group-addon">years</span>

              <div class="input-group col-xs-5 col-sm-3">
                <input formControlName="months" ">
                <span class="input-group-addon">months</span>
              </div>
            </div>
    </form>
      {{ form.get('years').value }}

现在您可以使ts

中的模型值为空