如何在Angular中使用父组件访问子组件表单数组值

时间:2018-10-30 09:11:34

标签: angular angular-reactive-forms

如何在Angular JS中通过父组件访问子组件表单数组值。

示例代码

 parent
    <div [formGroup]="createForm">
        <div formArrayName="pFormArray">
          <div *ngFor="let pFormArray of pFormArrayArray.controls; let j=index" [formGroupName]="j">
            {{ j }}

                <app-child [pForm]="pForm"></app-child>
                <!-- </div> -->
              </p-accordionTab>
            </p-accordion>
          </div>
        </div>
    </div>

child
     <div class="ui-fluid" [formGroup]="pForm">


        <div class="ui-g ui-g-nopad" *ngFor="let sForm of sFormArray.controls; 
        index as i; first as isFirst"

        [formGroupName]="i">
         <input type="text" formControlName="name"> 
        </div>
    </div>

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以使用ViewChild来引用您的子组件。

尝试以下代码

parent.component.html

<child #childRef></child>

parent.component.ts

@ViewChild('childRef') child : ChildComponent;

ngAfterViewInit(){
 console.log(this.child.getValue());
}

child.component.ts

getValue(){
 return 'value';
}

签出demo