用于清空angular2中的表单,“类型AbstractControl上不存在setValue”

时间:2016-10-08 05:35:06

标签: angular typescript

我的模板,

  <form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" novalidate="novalidate">
        <textarea [ngClass]="{ 'error': comment }"  
                  [formControl]="form.controls['comment']"  
                  placeholder="Comment...."></textarea>
    <div class="form-group">
       <button type="submit" id="template-contactform-submit" 
               name="template-contactform-submit"  
               value="submit">Enter</button>
    </div> 

我的TS:

for(var prop in form) {
   if(this.form.controls.hasOwnProperty(prop)) {
      this.form.controls[prop].setValue(" ");
   }
}

我收到的错误是“在AbstractControl类型上不存在setValue”。

2 个答案:

答案 0 :(得分:1)

尝试

(<FormControl>this.form.controls[prop]).setValue(" ");

还导入FormControl以使其正常工作

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

答案 1 :(得分:0)

我建议仔细检查你得到的错误。

首先,只是一个完整性检查 - 显示的错误信息是:

  

类型AbstractControl

上不存在setValue

Wile TS编译器会说

  

Property&#39; setValue&#39;类型&#39; AbstractControl&#39;

上不存在

因此,如果错误的方法调用确实是 setValue ,则不一致会导致保证,而不是其他。

其次 - setValue AbstractControl 上的 export abstract class AbstractControl { ... /** * Sets the value of the control. Abstract method (implemented in sub-classes). */ abstract setValue(value: any, options?: Object): void; 。查看AbstractControl source

w[1:]:  [-0.68  1.82]

X: [[ 3.3   0.  ]
    [ 3.32  0.  ]
    [ 3.34  0.  ]
      ..., 
    [ 7.94  6.08]
    [ 7.96  6.08]
    [ 7.98  6.08]]