Не удается добавить элементы управления динамически в controlarray

Я пытаюсь добавить вход динамически в форму, когда кто-то нажимает на кнопку.

Я нашел этот пример в официальных документах: Angular2 docs & plnker

Он работает с alpha.37, как вы можете видеть в плункере.

Я перевел это на rc1:

Составная часть:

import {FORM_DIRECTIVES, Location, Control, ControlGroup, ControlArray, Validators } from "@angular/common";
import {Component } from '@angular/core';

@Component({
    selector: 'my-app',
    templateUrl: 'app/partners/test.html',
    directives: [FORM_DIRECTIVES]
})

export class TestTest {
    ctrlFirst: Control = new Control('', Validators.required);
    ctrlMiddle: Control =  new Control('');
    ctrlLast: Control =  new Control('', Validators.required);
    ctrlFood: Control = new Control('pizza', Validators.required);
    ctrlCities: Control[] = [
        new Control(''),
        new Control(''),
        new Control('')
    ];
    citiesArray: ControlArray = new ControlArray(this.ctrlCities);

    formGroup: ControlGroup = new ControlGroup({
        name: new ControlGroup({
            first: this.ctrlFirst,
            middle: this.ctrlMiddle,
            last: this.ctrlLast
        }),
        food: this.ctrlFood,
        cities: this.citiesArray
    });

    get cgValue(): string {
        return JSON.stringify(this.formGroup.value, null, 2);
    }

    addCity(): void {
        this.citiesArray.push(new Control(''));
    }
}

Посмотреть:

<div>
    <h2>Angular2 Control &amp; ControlGroup Example</h2>
    <form [ngFormModel]="formGroup">
        <div [ngControlGroup]="name">
            <h3>Enter your name:</h3>
            <p>First: <input [ngControl]="first"><span *ngIf="!ctrlFirst.valid"> [required]</span></p>
            <p>Middle: <input [ngControl]="middle"></p>
            <p>Last: <input [ngControl]="last"><span *ngIf="!ctrlLast.valid"> [required]</span> </p>
        </div>
        <h3>What's your favorite food?</h3>
        <p><input [ngControl]="food"><span *ngIf="!ctrlFood.valid"> [required]</span></p>
        <h3>Name a few cities:</h3>
        <ul [ngFormControl]="cities">
            <li *ngFor="let ctrl of ctrlCities; let i = index"><input [ngControl]="i"></li>
        </ul>
        <button type="button" (click)="addCity()">Add a city</button>

    </form>
    <h3>Value:</h3>
    <pre>{{ cgValue }}</pre>
    <h3>Validity:</h3>
    <pre>{{ formGroup.valid }}</pre>
</div>

Когда я пытаюсь запустить это, я получаю следующую ошибку:

EXCEPTION: Error in app/partners/test.html:3:13
browser_adapter.ts:78EXCEPTION: Error in app/partners/test.html:3:13BrowserDomAdapter.logError @ browser_adapter.ts:78
browser_adapter.ts:78ORIGINAL EXCEPTION: Cannot find control ''BrowserDomAdapter.logError @ browser_adapter.ts:78
browser_adapter.ts:78ORIGINAL STACKTRACE:BrowserDomAdapter.logError @ browser_adapter.ts:78
browser_adapter.ts:78Error: Cannot find control ''
    at new BaseException (exceptions.ts:14)
    at _throwError (shared.ts:61)
    at Object.setUpControlGroup (shared.ts:54)
    at NgFormModel.addControlGroup (ng_form_model.ts:76)
    at NgControlGroup.ngOnInit (ng_control_group.ts:39)
    at DebugAppView._View_TestTest0.detectChangesInternal (TestTest.template.js:418)
    at DebugAppView.AppView.detectChanges (view.ts:243)
    at DebugAppView.detectChanges (view.ts:345)
    at DebugAppView.AppView.detectViewChildrenChanges (view.ts:267)
    at DebugAppView.AppView.detectChangesInternal (view.ts:256)BrowserDomAdapter.logError @ browser_adapter.ts:78
browser_adapter.ts:78ERROR CONTEXT:BrowserDomAdapter.logError @ browser_adapter.ts:78
browser_adapter.ts:78DebugContextBrowserDomAdapter.logError @ browser_adapter.ts:78
zone.js:463 ViewWrappedException

1 ответ

Вы можете добавить элемент управления следующим образом:

this.foo = fb.group({
    Data1: [""],
    Data2: [""],
})

this.ControlGroup = new Control();
this.foo.addControl('Data3', this.ControlGroup);
Другие вопросы по тегам