簡體   English   中英

angular 中的嵌套動態表單 - 無法讀取未定義的屬性“控件”

[英]Nested dynamic form in angular - Cannot read property 'controls' of undefined

我正在嘗試建立一個網站,提供上傳您自己的課程的功能。

課程結構

    Name of course
    |-Module1
      |-Lecture1
      |-Lecture2
    |-Module2
      |-Lecture1
      |-Lecture2

使用 Angular 我正在嘗試創建一個動態表單,它將在課程中添加/刪除模塊並在模塊中進行講座

到目前為止,我已經寫了以下內容 -

課程上傳.component.ts

export class CourseUploadComponent implements OnInit {

    courseUploadForm: FormGroup;

    constructor(private formBuilder: FormBuilder) { }

    ngOnInit() {
        this.courseUploadForm = this.formBuilder.group({
            coursename: ['', Validators.required],
            modules: this.formBuilder.array([
                this.initModules()
            ])
        })
    }

    initModules() {
        return this.formBuilder.group({
            modulename: ['', Validators.required],
            lectures: this.formBuilder.array([
                this.initLecture()
            ])
        });
    }

    initLecture() {
        return this.formBuilder.group({
            lecturename: ['', Validators.required],
            description: ['', Validators.required],
            lecture: ['', Validators.required]
        });
    }

    addModule() {
        const control = <FormArray>this.courseUploadForm.get('modules');
        control.push(this.initModules());
    }

    addLecture() {
        const control = <FormArray>this.courseUploadForm.get('lectures');
        control.push(this.initLecture());
    }

    removeModule(i: number) {
        const control = <FormArray>this.courseUploadForm.get('modules');
        control.removeAt(i);

    } 

    removeLecture(i: number) {
        const control = <FormArray>this.courseUploadForm.get('lectures');
        control.removeAt(i);
    }

    getModulesControls(i: number) {
        >>>> return [(this.courseUploadForm.controls.modules as FormArray).controls[i]['controls']];
    }

    getLecturesControls(i: number) {
        return [(this.courseUploadForm.controls.lectures as FormArray).controls[i]['controls']];
    }

}

課程上傳.component.html

<form [formGroup]="courseUploadForm" novalidate>

    <div formArrayName="modules">

        <mat-card *ngFor="let module of courseUploadForm.get('modules').value; let i=index">

            <mat-card-subtitle>
                {{i+1}}
            </mat-card-subtitle>

            <div [formGroupName]="i">

                <mat-form-field>
                    <mat-label>Module Name</mat-label>
                   **>>>** <input matInput placeholder="Module Name" formControlName="modulename">
                    <ng-container *ngFor="let control of getModulesControls(j)">
                        <mat-error *ngIf="!control.name.valid">Name Required</mat-error>
                    </ng-container>
                </mat-form-field>

                <div formArrayName="lectures">

                    <mat-card *ngFor="let lecture of module.get('lectures').value; let j=index">

                        <mat-card-subtitle>
                            Lecture {{i+1}}: {{lecture.name}}
                        </mat-card-subtitle>

                        <div [formGroupName]="j">

                            <mat-form-field>
                                <mat-label>Name</mat-label>
                                <input matInput placeholder="Lecture Name" formControlName="lecturename">
                                <ng-container *ngFor="let control of getLecturesControls(j)">
                                    <mat-error *ngIf="!control.name.valid">Name Required</mat-error>
                                </ng-container>
                            </mat-form-field>

                            <mat-form-field>
                                <mat-label>Description</mat-label>
                                <input matInput placeholder="Lecture Description" formControlName="description">
                                <ng-container *ngFor="let control of getLecturesControls(j)">
                                    <mat-error *ngIf="!control.description.valid">Description Required</mat-error>
                                </ng-container>
                            </mat-form-field>

                            <mat-form-field>
                                <mat-label>Lecture</mat-label>
                                <input matInput placeholder="Lecture Video" formControlName="lecture">
                                <ng-container *ngFor="let control of getLecturesControls(j)">
                                    <mat-error *ngIf="!control.lecture.valid">Lecture Video Required</mat-error>
                                </ng-container>
                            </mat-form-field>
                            <mat-card-actions>
                                <button mat-raised-button color="accent" (click)="addLecture()">Add Another
                                    Lecture</button>
                                <button mat-raised-button color="warn"
                                    *ngIf="module.get('lectures')['controls'].length > 1"
                                    (click)="removeLecture(j)">Remove This Lecture</button>
                            </mat-card-actions>
                        </div>

                    </mat-card>

                </div>
                <mat-card-actions>
                    <button mat-raised-button color="accent" (click)="addModule()">Add Another Module</button>
                    <button mat-raised-button color="warn"
                        *ngIf="courseUploadForm.get('modules')['controls'].length > 1" (click)="removeModule(i)">Remove
                        This Module</button>
                </mat-card-actions>
            </div>

        </mat-card>

    </div>

</form>

我得到錯誤:

Cannot read property 'controls' of undefined

at CourseUploadComponent.getModulesControls 

at CourseUploadComponent_mat_card_2_Template 

我用 ** > ** 突出顯示了引發錯誤的行

一些幫助?

j在這里沒有定義它應該是 smg 不同的

<ng-container *ngFor="let control of getModulesControls(j)">
    <mat-error *ngIf="!control.name.valid">Name Required</mat-error>
</ng-container>

我想你打算在那里使用變量igetModulesControls(i)

此外,HTML 文件的第 5 行,變量module定義為 Object。 第 23 行module.get('lectures')看起來您希望module變量中有一個FormGroup 看看Angular 文檔中的這個例子 注意 HTML 標記和 TS。 您將需要創建幾個 getter,例如get cities(): FormArray (:

我認為您必須檢查給定的數組是否為空。 如果為空,則應返回 null,

    getModulesControls(i: number) {
         if(this.courseUploadForm.controls.modules.length <1){
              return null;
         }
         else{
             return [(this.courseUploadForm.controls.modules as FormArray).controls[i]['controls']];
         }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM