简体   繁体   English

为什么我收到一条错误消息,指出错误 TS2339:类型“AbstractControl”上不存在属性“控件”

[英]Why do i get an error saying error TS2339: Property 'controls' does not exist on type 'AbstractControl'

Going round in circles here all the articles and questions here advise referring to controls property in the template for a form array in an Angular 9 project.在这里绕圈子这里的所有文章和问题都建议在 Angular 9 项目中引用表单数组模板中的控件属性。

However i get an error saying controls property does not exist.但是我收到一条错误消息,指出控件属性不存在。 All of my data is pulling through to the form its just this compile error thats throwing me.我所有的数据都被转化为表单,它只是抛出我的这个编译错误。

Template模板

<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>

Component成分

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;
      }
}

Person Model人物模型

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'}];
        }
    }

}

This was a tough one to solve thanks @bjdose.感谢@bjdose,这是一个很难解决的问题。

After reviewing many solutions I have now put together some code that works for anyone else having this problem.在查看了许多解决方案之后,我现在整理了一些适用于遇到此问题的其他人的代码。

Template模板

<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 CODE代码

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TS2339:“AbstractControl”类型上不存在属性“控件” - TS2339: Property 'controls' does not exist on type 'AbstractControl' 错误 TS2339:类型“Observable”上不存在属性“do” - error TS2339: Property 'do' does not exist on type 'Observable< TS2339:“行为主题”类型上不存在属性“排序” - TS2339: Property 'sort' does not exist on type 'BehaviorSubject<AbstractControl[] 为什么会出现错误TS2339:类型“主题”上不存在属性“扫描” <any> “? - Why am I getting error TS2339: Property 'scan' does not exist on type 'Subject<any>'? 如何解决错误“TS2339:&#39;JQuery 类型上不存在属性&#39;仪表&#39;<HTMLElement> &#39;。” - How do I resolve error "TS2339: Property 'gauge' does not exist on type 'JQuery<HTMLElement>'." 错误TS2339:类型“无效”上不存在属性“ _ws” - error TS2339: Property '_ws' does not exist on type 'void' 错误TS2339:类型“ {}”上不存在属性“ hometeam” - error TS2339: Property 'hometeam' does not exist on type '{}' 错误 TS2339:“订阅”类型上不存在属性“订阅” - error TS2339: Property 'subscribe' does not exist on type 'Subscription 错误 TS2339:属性“flatMap”在类型“any”上不存在 - error TS2339: Property 'flatMap' does not exist on type 'any 错误 TS2339:“响应”类型上不存在属性“结果” - error TS2339: Property 'results' does not exist on type 'Response'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM