Angular 5 - 模板错误:“AbstractControl”类型中不存在“属性'长度'”

时间:2018-03-04 12:44:06

标签: angular build

当尝试使用命令ng build --prod --output-path <my_destination_path>构建我的Angular项目时,我得到的错误如下:

ERROR in src/app/products/product-edit/product-edit.component.html(190,10): : Property 'length' does not exist on type 'AbstractControl'.

模板product-edit.component.html :(错误在第1行)

<div *ngIf="productForm.get('seasons').length>0; else infoTextNoSeasons" formArrayName="seasons">
              <div class="row" *ngFor="let seasonCtrl of productForm.get('seasons').controls; let i = index"
          [formGroupName]="i">
                <div [class.col-xs-10]="i!=0">
                  <div [class.row]="i!=0">
                          <div class="form-group col-sm-12">
                            <label class="sr-only" for="season">Season</label>
                            ...

由于应用程序使用ng serve正常工作,我不知道为什么Angular无法构建它。

1 个答案:

答案 0 :(得分:3)

使用--prod标志时,您正在使用AOT编译器。

与在浏览器中运行并将模板编译为JavaScript的JIT编译器不同,AOT编译器在构建期间运行,将模板编译为TypeScript,然后将TypeScript编译为JavaScript。

因此,TypeScript类型检查apply,允许在编译时而不是运行时发现模板中的错误。

错误消息告诉您错误:您正在尝试从AbstractControl访问length属性,但AbstractControl没有这样的属性。 length仅存在于FormArray中,但TypeScript无法知道AbstractControl是FormArray。因此,在组件中添加一个使用类型断言并返回长度的方法。