【问题标题】:Why do i get an error saying error TS2339: Property 'controls' does not exist on type 'AbstractControl'为什么我收到一条错误消息:错误 TS2339:“AbstractControl”类型上不存在属性“控件”
【发布时间】:2020-06-27 19:21:03
【问题描述】:

在这里转圈,这里的所有文章和问题都建议在 Angular 9 项目中为表单数组引用模板中的控件属性。

但是我得到一个错误,说控件属性不存在。我所有的数据都被拉到表单中,这就是抛出我的编译错误。

模板

<form name="mainForm" [formGroup]="mainForm">
   <div formArrayName="phoneNumbers" *ngFor="let item of mainForm.get('phoneNumbers').controls; let i = index">
      <div [formGroupName]="i">
         <input formControlName="label" />
         <input formControlName="number" />
      </div>
   </div>
</form>

组件

import { Person } from "@shared/models/person.model";
import { DataService } from "../services/people-data-service";
import {
    Component,
    OnInit,
    ViewEncapsulation,
    ChangeDetectionStrategy,
    Inject
} from "@angular/core";
import { FormBuilder, FormGroup, FormArray, FormControl } from "@angular/forms";
import { ActivatedRoute, Router } from "@angular/router";
import { fuseAnimations } from "@fuse/animations";

@Component({
    selector: "fw-person",
    templateUrl: "./person.component.html",
    styleUrls: ["./person.component.scss"],
    encapsulation: ViewEncapsulation.None,
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class PersonComponent implements OnInit{
    id: string;
    entity: Person;
    pageType: string;
    mainForm: FormGroup;

    constructor(
        @Inject("PeopleService")
        private _dataService: DataService<Person>,
        private _activatedRoute: ActivatedRoute,
        private _formBuilder: FormBuilder,

    ) {
        this.entity = new Person();
    }

    ngOnInit(): void {
        this.id = this._activatedRoute.snapshot.params["id"];

        if (this.id !== "new") {
            this._dataService.getByKey(this.id).subscribe(entity => {
                this.entity = new Person(entity);
                this.updateFormFields(entity);
                this.pageType = "edit";
                });
        } else {
            this.pageType = "new";
            this.entity = new Person();
        }

        this.mainForm = this.createPersonForm();

    }

    createPersonForm(): FormGroup {
        return this._formBuilder.group({
            firstName: [this.entity.firstName],
            familyName: [this.entity.familyName],
            phoneNumbers: this._formBuilder.array([]),
        });
    }

    updateFormFields(entity): void {
        Object.keys(this.mainForm.controls).forEach(key => {
            this.mainForm.controls[key].patchValue(entity[key]);
        });
    }

    get phoneNumbers() {
        return this.mainForm.get('phoneNumbers') as FormArray;
      }
}

人物模型

export class Person{
    firstName: string;
    familyName: string;
    phoneNumbers: [{
        label: string,
        number: string
    }];

    constructor(person?) {
        {
            this.firstName = person.firstName || '';
            this.familyName = person.familyName || '';
            this.fullName = person.firstName + ' ' + person.familyName || '';
            this.phoneNumbers = person.phoneNumbers || [{label:'Work', number:'123'}];
        }
    }

}

【问题讨论】:

  • 你能在 stackblitz 上发布你的代码吗?
  • @bjdose stackblitz.com/edit/angular-mc7s3t 有趣的是,我没有收到编译错误,但我也无法访问我的 *ngFor 中的任何数据
  • 您无法访问 *ngFor 中的任何数据,因为该数组已初始化为空数组。
  • 当然 - 谢谢。并没有真正解释为什么它在我的实际项目中不起作用。但我有一个可以使用的工作版本 - 非常感谢您的帮助
  • 我在一个真实的项目中编写了代码,我看到了这个问题,我在这里找到了一些解决方案:github.com/angular/angular-cli/issues/6099 和另一个更易于阅读的解决方案:stackoverflow.com/questions/46926182/…

标签: angular angular-reactive-forms


【解决方案1】:

感谢@bjdose,这是一个很难解决的问题。

在查看了许多解决方案后,我现在整理了一些适用于其他遇到此问题的人的代码。

模板

<form name="mainForm" [formGroup]="mainForm">
     <div formArrayName="phoneNumbers">
         <div *ngFor="let phoneNumber of getPhoneNumbers(); let i = index">
             <div [formGroupName]="i">
                 <mat-form-field>
                    <mat-label>Label</mat-label>
                        <input matInput placeholder="Label" name="label" 
                            formControlName="label"/>
                    </mat-form-field>

                    <mat-form-field>
                        <mat-label>Number</mat-label>
                            <input matInput placeholder="Number" name="number" 
                                 formControlName="number"/>

                    </mat-form-field>
                     <button mat-raised-button type="button"
                                  (click)="addPhoneNumber()">Add</button>

                     <button mat-raised-button type="button"
                                  (click)="removePhoneNumber(i)">Remove</button>
                 </div>
           </div>
     </div>
</form>

TS 代码

import { FormBuilder, FormGroup, FormArray, FormControl } from "@angular/forms";
import { ActivatedRoute, Router } from "@angular/router";

@Component({
    selector: "fw-person",
    templateUrl: "./person.component.html",
    styleUrls: ["./person.component.scss"],

})
export class PersonComponent implements OnInit {

id: string;
mainForm: FormGroup;
entity: Person;

constructor(

        private _formBuilder: FormBuilder,


    ) {
        this.entity = new Person();


    }

ngOnInit(): void {
        this.id = this._activatedRoute.snapshot.params["id"];

        this.country = _.find(this.countries, {
            id: this._translateService.currentLang
        });

        if (this.id !== "new") {
            this._dataService.getByKey(this.id).subscribe(entity => {
                this.entity = new Person(entity);

                this.updateFormFields(entity);

            });
        } else {
            this.pageType = "new";
            this.entity = new Person();
        }

        this.mainForm = this.createPersonForm();


    }

createPersonForm(): FormGroup {
        return this._formBuilder.group({
            id: [this.entity.id],
            code: [this.entity.code],
            firstName: [this.entity.firstName],
            familyName: [this.entity.familyName],
            handle: [this.entity.handle],
            companyId: [this.entity.companyId],
            phoneNumbers: this._formBuilder.array([this.newPhoneNumber()]),
            tags: [this.entity.tags],
            images: this._formBuilder.array([this.entity.images]),
            active: [this.entity.active]
        });
    }

updateFormFields(entity): void {
        Object.keys(this.mainForm.controls).forEach(key => {
            this.mainForm.controls[key].patchValue(entity[key]);
        });
    }

newPhoneNumber(): FormGroup {
        return this._formBuilder.group({
            label: "",
            number: ""
        });
    }

    addPhoneNumber() {
        (this.mainForm.get("phoneNumbers") as FormArray).push(
            this.newPhoneNumber()
        );
    }

    removePhoneNumber(i: number) {
        (this.mainForm.get("phoneNumbers") as FormArray).removeAt(i);
    }

    getPhoneNumbers(): any {
        return (this.mainForm.get("phoneNumbers") as FormArray).controls;
    }
}

【讨论】:

  • 请解释你的答案的不同之处
  • @Andrew 对不起,请澄清你在问什么?
  • 您的回答不包含任何解释...即有问题的代码和答案中的代码有什么不同
猜你喜欢
  • 2021-08-13
  • 2019-10-17
  • 2019-06-06
  • 2018-11-13
  • 2019-01-21
  • 2016-08-13
  • 1970-01-01
  • 2017-12-20
  • 2020-10-11
相关资源
最近更新 更多