Javascript 角度2+;打字脚本可以';在编译时找不到属性
我正在尝试在angular 2中构建一个自定义表单验证方法。 问题是,当我运行该项目时,会出现以下错误:Javascript 角度2+;打字脚本可以';在编译时找不到属性,javascript,angular,typescript,Javascript,Angular,Typescript,我正在尝试在angular 2中构建一个自定义表单验证方法。 问题是,当我运行该项目时,会出现以下错误: Property 'controls' does not exist on type 'AbstractControl'. 但是如果我忽略它并继续使用我的应用程序,我会看到验证功能按计划工作 还有其他人面临这个问题吗?为什么我会犯这样的错误? 我用的gassing与typescript有关,而不是角度本身(我用的是typescript2.0.3) 这是我的代码: 进口: import {I
Property 'controls' does not exist on type 'AbstractControl'.
但是如果我忽略它并继续使用我的应用程序,我会看到验证功能按计划工作
还有其他人面临这个问题吗?为什么我会犯这样的错误?
我用的gassing与typescript有关,而不是角度本身(我用的是typescript2.0.3)
这是我的代码:
进口:
import {Injectable} from '@angular/core';
import {RegexService} from "./regex.service";
import {FormControl, ValidatorFn} from "@angular/forms";
自定义验证功能:
requireGroupMinAmount(minPossibleAmount): ValidatorFn {
return (control: FormControl): string[]=> {
let requireCounter = 0;
if (!control)
return null;
controlsLoop:for (let formOptionKey in control.controls) {
for (let formOptionValue in control.controls[formOptionKey].controls) {
if (control.controls[formOptionKey].controls[formOptionValue].value)
requireCounter++;
if (requireCounter >= minPossibleAmount)
break controlsLoop;
}
}
return requireCounter >= minPossibleAmount
? null
: ["Please fill at least " + minPossibleAmount + " fields"];
}
}
提前感谢。子集合/字典
控件
是在派生类FormGroup
和FormArray
上定义的。因此,如果我们想迭代FormGroup
(其中控件属于dictionary类型),我们需要执行以下检查:
if (control instanceof FormGroup)
{
controlsLoop:for (let formOptionKey in control.controls) {
...
}
}
只有当抽象控件是FormGroup
实例时,编译器(甚至运行时)才会正确迭代
此外,我们必须确定,即将到来的值是AbstractControl
requireGroupMinAmount(minPossibleAmount): ValidatorFn {
//return (control: FormControl): string[]=> {
return (control: AbstractControl): string[]=> {
而不是子类型FormControl。只能正确检查抽象基是否属于其某些子类型(例如FormArray)
有一个经过调整的代码段():
我很困惑。。控件不应为“FormControl”类型?这就是我定义的类型。。不管怎样,我已经尝试用'FormArray'和'FormGroup'添加您的if语句,但是我在编译时仍然遇到这个错误。.FormControl永远不会是FormArray。只有如果您使用AbstractControl。。您可以检查它是否属于子类型FormArray。所以,不要使用FormControl。。。如果控制组真的有孩子。如果存在som子控件。。它不是FormArray就是FormGroup。签入回答显示了如何检查抽象控件。。。(应该是验证程序的值)是预期的子类型OK。。现在更清楚了。。但即使我将类型从formControl更改为formGroup并添加if语句,也会得到相同的错误。几乎如果编译器忽略从FormControl到AbstractControl的if。。那是那三个孩子的父母。。无法组成组…仍然无法工作。。即使我添加了control.hasOwnProperty(“controls”)之类的内容,它仍然会给我一个错误。。
requireGroupMinAmount(minPossibleAmount): validatorFn{
return (control: AbstractControl): string[] => {
let requireCounter = 0;
if (!control)
return null;
if (control instanceof FormGroup) {
controlsLoop: for (let formOptionKey in control.controls) {
var childControl: AbstractControl = control.controls[formOptionKey];
if (childControl instanceof FormGroup) {
for (let formOptionValue in childControl.controls) {
if (childControl.controls[formOptionValue].value)
requireCounter++;
if (requireCounter >= minPossibleAmount)
break controlsLoop;
}
}
}
}
return requireCounter >= minPossibleAmount
? null
: ["Please fill at least " + minPossibleAmount + " fields"];
}
}