【问题标题】:Angular 2 - Accessing Nested Formarrays (FormBuilder)Angular 2 - 访问嵌套的 Formarrays (FormBuilder)
【发布时间】:2017-08-19 05:49:44
【问题描述】:

我正在使用 Angular 2 ReactiveForms 创建一个表单。该表格由模板、问题和答案组成。一个模板包含许多问题,问题包含许多答案。

ngOnInit() {
    // initialize template
    this.myForm = this.formBuilder.group({
        title: ['', [Validators.required, Validators.minLength(5), Validators.maxLength(30)]],
        owner: [localStorage.getItem('user')],
        questions: this.formBuilder.array([
            this.initQuestion()
        ])
    }); 
}

initQuestion() {
    // initialize question
    return this.formBuilder.group({
        questionText: [{value: '', disabled: true}],
        answers: this.formBuilder.array([
            this.initAnswer()
        ])
    });
}

initAnswer() {
    // initialize answer
    return this.formBuilder.group({
        answerText: [{value: '', disabled: true}]
    });
}

addQuestion() {
    const control = <FormArray>this.myForm.controls['questions'];
    console.log(control);
    control.push(this.initQuestion());
}

addAnswer() {
    const control = <FormArray>this.myForm.get(['questions.0.answers']);
    control.push(this.initAnswer());
}

我的目标是允许用户向模板添加问题,并回答每个问题。然而,我的问题是我无法访问名为“answers”的嵌套数组。到目前为止,我可以添加问题并且工作正常,但是当我尝试添加问题的答案(addAnswer() 方法)时,我收到一条错误消息,提示“无法读取属性‘push’ of null” ,它在 addAnswer() 方法中引用 control.push。任何帮助表示赞赏!

编辑:忘记添加我的 HTML 代码:

<table class=pageTable align=center border="1px">
    <form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm)" align=center>
        <!-- we will place our fields here -->
        <input type="submit" [disabled]="!myForm.valid" value="Submit Template">

        <!-- Template Title -->
        <div class="form-group">
            <label>Template Title:</label><br/>
            <input type="text" formControlName="title"><br/>
            <!--display error message if name is not valid-->
            <small *ngIf="!myForm.controls.title.valid" class="text-danger">
                Title must be between 5-30 characters.
            </small>
        </div>

        <br/>

        <!-- List of Questions -->
        <div formArrayName="questions" align=center>
            <div [formGroupName]="i" *ngFor="let question of myForm.controls.questions.controls; let i=index" class="Question-panel">
                <div class="Question-panel-title">
                    <span>Question {{i + 1}}:</span>
                    <!-- show remove button when more than one address available -->
                    <span *ngIf="myForm.controls.questions.controls.length > 1"  
                        (click)="removeQuestion(i)">
                    </span>
                    <question [group]="myForm.controls.questions.controls[i]"></question>
                </div>

                <!-- Llist of Answers -->
                <div formArrayName="answers" align=center>
                    <div [formGroupName]="j" *ngFor="let answer of question.controls.answers.controls; let j=index">
                        <div class="Question-panel-content">
                            <span>Answer {{j + 1}}:</span>
                            <br/><a (click)="addAnswer()" style="cursor: default">
                                Add answer
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <br/>

        <a (click)="addQuestion()" style="cursor: default">
            Add question
        </a>
    </form>
</table>

【问题讨论】:

    标签: angular forms nested


    【解决方案1】:

    我认为你应该使用字符串

    this.myForm.get('questions.0.answers')
    

    或类似数组

    this.myForm.get(['questions', 0, 'answers']);
    

    更新

    根据你的html

    addAnswer(idx: number) {
      const control = <FormArray>this.myForm.get(['questions', idx, 'answers']);
      control.push(this.initAnswer());
    }
    

    在html中

    <a (click)="addAnswer(i)">Add answer</a>
    

    另见

    【讨论】:

    • 感谢您的解决方案,它引导我走向正确的道路。 this.myForm.get('questions.0.answers') 几乎可以按预期工作,但是您是否知道一种为相应问题添加答案的方法?因为无论我决定在哪个问题上添加答案,只有收到的第一个问题才会添加新答案,因此是“question.0.answers”。我刚刚在帖子中添加了我的 HTML :)
    • 你我的好先生是救世主。非常感谢,祝您有美好的一天!
    猜你喜欢
    • 2018-01-12
    • 2017-02-22
    • 2017-08-14
    • 1970-01-01
    • 2017-12-21
    • 2018-10-11
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    相关资源
    最近更新 更多