【问题标题】:How to access child component form array values with-in parent componet in Angular如何在Angular中的父组件中访问子组件表单数组值
【发布时间】:2018-10-30 18:25:16
【问题描述】:

如何在 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

【问题讨论】:

  • 那么您使用的是 Angular(新框架)还是 AngularJS(旧框架)?请相应地编辑标签和您的标题。

标签: angular angular-reactive-forms


【解决方案1】:

您可以使用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

【讨论】:

  • 如果我们使用,这适用于一个子组件。我的情况是同时使用表单数组(多个)子组件和父组件。如果我们得到这样的 @ViewChild('childRef') child : ChildComponent;只有一个孩子回来。你有什么主意吗 ??。谢谢
猜你喜欢
  • 2019-06-26
  • 1970-01-01
  • 2020-07-10
  • 2019-02-28
  • 1970-01-01
  • 2017-11-12
  • 2023-03-27
  • 1970-01-01
  • 2019-08-30
相关资源
最近更新 更多