Как использовать реактивную форму в нескольких дочерних компонентах Angular 6? - PullRequest
1 голос
/ 15 марта 2019

Это код файла parent.component.ts.

ngOnInit() {
    this.myForm = this._fb.group({
        name: ['', Validators.required],
        description: ['', Validators.required],
        status: ['', Validators.required],
        startTime: ['', Validators.required],
        recurrence: [],
    });
    this.secondForm = this._fb.group({
        items: this._fb.array([
            this.initAddress(),
        ])
    });
 }

 initAddress() {
    return this._fb.group({
        EmailType: ['', Validators.required],
        templateName: ['', Validators.required],
        notesDescription: ['', Validators.required],
        name: ['', Validators.required],
        template: this._fb.array([
            {
                displayFromName: new FormControl('', Validators.required)
            }
        ]),

        'numberOfDaysToWait': ['', Validators.required],
        'sequentialOrder': ['', Validators.required]
    });
}

HTML-код файла parent.component.html. Пожалуйста, игнорируйте различные условия в форме, которую я использовал для проекта.

 <form [formGroup]="secondForm" (ngSubmit)="onSecondSubmit()" *ngIf="EnableSecond" [hidden]="!myForm.valid">

            <div formArrayName="items" class="remove-link accordian-style">
                <div class="btm-brdr">
                    <p>WorkFlow Template</p>
                </div>
                <div *ngFor="let address of secondForm.get('items')['controls']; let i=index;">
                    <nb-accordion>
                        <nb-accordion-item>
                            <nb-accordion-item-header>

                                <div class="col-md-12 row">
                                    <div class="col-md-11">
                                        <label> Email Template - {{i + 1}}</label>
                                    </div>
                                    <div class="col-md-1">
                                        <span *ngIf="secondForm.controls.items.controls.length > 1" (click)="removeAddress(i)" class="removelink"> Remove
                                        </span>
                                    </div>
                                </div>
                            </nb-accordion-item-header>
                            <nb-accordion-item-body>
                                <address class="form-width" [group]="secondForm.controls.items.controls[i]" [itemIndex]="i" [newgroup]="secondForm.controls.items"></address>
                            </nb-accordion-item-body>
                        </nb-accordion-item>
                    </nb-accordion>
                </div>
            </div>
            <div class="row">
                <a class="a-link" (click)="addAddress()">
                    Create More Email Template
                </a>
            </div>
            <div>
                <div>

                    <button nbButton type="submit" [disabled]="!secondForm.valid">Confirm</button>
                </div>
            </div>
        </form>

эти поля будут заполнены в child.component.html. Здесь вы снова увидите цикл displayFromName. Но когда я отправляю форму, я не могу получить значения.

div [formGroup]="adressForm">
<div class="form-group row" *ngIf="ShowOption">
    <select class="form-control" name="EmailType" formControlName="EmailType" (change)="SelectedOption($event)" required>
        <option [ngValue]=" ">Create New</option>
        <option *ngFor="let list of Optionmodel" [ngValue]="list.name">
            {{list.name}}
        </option>
    </select>
</div>
<div *ngIf="ShowList">


    <div class="form-group row">
        <label for="name" class="col-sm-3 col-form-label">Template Name</label>
        <div class="col-sm-9">
            <input nbInput type="text" id="name" class="full-width" placeholder="Enter Name" name="name" formControlName="name" [readonly]="isreadonly"
                [(ngModel)]="model.name" required>
            <show-errors [control]="adressForm.controls.name"></show-errors>
        </div>
    </div>
    <div class="form-group row">
        <label for="templateName" class="col-sm-3 col-form-label">Name</label>
        <div class="col-sm-9">
            <input nbInput type="text" id="templateName" class="full-width" placeholder="Enter Name" name="templateName" formControlName="templateName"
                [(ngModel)]="model.templateName" required>
            <show-errors [control]="adressForm.controls.templateName"></show-errors>
        </div>
    </div>
    <div class="form-group row">
        <label for="notesDescription" class="col-sm-3 col-form-label">Notes/Description</label>
        <div class="col-sm-9">
            <textarea nbInput type="text" id="notesDescription" class="full-width" placeholder="Enter Name" name="notesDescription" formControlName="notesDescription"
                [(ngModel)]="model.notesDescription" required></textarea>
            <show-errors [control]="adressForm.controls.notesDescription"></show-errors>
        </div>
    </div>

    <div *ngFor="let z of adressForm.controls['template'].controls; let i = index;" class="remove-link edit-workflow-template-block mrgn-btm-10">
        {{z[i] | json}}
        <div class="form-group row">
            <label for="displayFromName" class="col-sm-3 col-form-label">From Name</label>
            <div class="col-sm-9">
                <input nbInput type="text" id="displayFromName" class="full-width" placeholder="From Name" name="z[i].displayFromName" formControlName="z[i].displayFromName"
                    required>
                <!-- <show-errors [control]="adressForm.controls.displayFromName"></show-errors> -->
            </div>
        </div>

        <!-- <template-details-fields [form]="myForm" [item]="item" [itemIndex]="i"  [groups]="myForm.controls.template.controls[i]"></template-details-fields> -->

    </div>
    <div class="row">
        <a class="a-link" (click)="addAddress1()">
            Create More locale
        </a>
    </div>

Файл Child.component.ts, в котором я создал код для отправки массива в displayFromName.

@Input('group')
public adressForm: FormGroup;
@Input() itemIndex: number;
@Input() newgroup: number;

addAddress1() {
    const control = this.newgroup['controls'][this.itemIndex].controls['template'];
    console.log(control);
    control.push(this.initAddress1());
    console.log(control);
}
initAddress1() {
   const control =  this._fb.array([
        {
            displayFromName: new FormControl('', Validators.required)
        }
    ]);
   return control['controls'][0];
}

Когда я отправляю значение, я, наконец, получил это. enter image description here

Но вывод должен быть

template :[
{
displayFromName:"test" 
},
{
displayFromName:"test1" 
}
]
...