Angular-从父类中调用子组件函数

时间:2020-09-02 19:23:27

标签: angular angular-reactive-forms angular-directive angular-components

我有一个与两个子模板集成在一起的父类(一个模板中包含3个单独的表单详细信息)。 表单格式示例如下:

父母表格

  • 儿童表格 (添加子项A详细信息)(删除子项A详细信息)
  • 儿童B表格 (添加子B详细信息)(删除子B详细信息)

添加家长表格。

在上面的示例中,我能够使用formarray和formbuilder成功复制表单元素。但是,当我单击“添加子项A详细信息”时,它应该复制子项B表单下的表单元素,但是在当前设计中,它会在子项B之前重复。

为了满足上述要求,我尝试在父窗体中添加两个子功能的“添加”按钮,并尝试使用Input Decorator与子类进行交互。但是我不确定如何将click事件发送到子窗体以触发从父类添加子窗体的功能。

父母表格:

<app-child-A [addDetail()]></app-child-A>

<div class="form-group row mb-2">
      <div class="col-md-4">
        <button class="btn btn-outline-primary"
                type="button" style="margin-left:10px; font-size: 12px;"
                (click)="addDetail()">
          Add Details
        </button>
      </div>
    </div>

孩子A:

eventForm: FormGroup;
constructor(private fb: FormBuilder) { }

 ngOnInit(): void {
    this.eventForm=this.fb.group({
      eventDetails: this.fb.array([this.buildDetail()])
    }); 
  }
  get eventDetails(): FormArray {
    return this.travelForm.get('travellerDetails') as FormArray;
  }
 @Input() addDetail(): void {
    this.eventDetails.push(this.buildDetail());
  }
 buildDetail(): FormGroup {
    return this.fb.group({
      eventName: '',
      desc: '',
      start: '',
      reach: '',
      transport: '',
      cost:null
    });
  }

我是Angular的新手,请帮忙,如果还有其他实现需求的方法来代替Input装饰器,请告诉我。

谢谢!

1 个答案:

答案 0 :(得分:0)

我们可以通过多种方式实现组件之间的交互作用。

  1. 使用@Input [属性绑定],@Output(事件发射)
  2. 使用Rxjs可观察/对象
  3. 使用Local/Session/Cache Storage

我希望这个 Demo 应用程序满足您的要求。

在上面的演示中,我创建了如下共享服务

import { Injectable } from "@angular/core";
import {Observable, BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AppService {
  public eventFormChange = new BehaviorSubject<any>(null);

  triggerFormChange(data: any) {
    this.eventFormChange.next(data);
  }

  formChangeEvent() {
    return this.eventFormChange.asObservable();
  }
}

父组件(应用程序组件)将更新后的表单馈送到共享服务,如下所示。

import { Component } from '@angular/core';
import{FormGroup, FormBuilder, FormArray} from '@angular/forms';
import { AppService } from './app.service';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  eventForm: FormGroup;
constructor(private fb: FormBuilder,
private appService:AppService
) { }

 ngOnInit(): void {
    this.eventForm=this.fb.group({
      eventDetails: this.fb.array([this.buildDetail()])
    }); 
    this.updateForm();
  }

get eventDetails(): FormArray {
    return this.eventForm.get('eventDetails') as FormArray;
  }

  buildDetail(): FormGroup {
    return this.fb.group({
      eventName: '',
      desc: '',
      start: '',
      reach: '',
      transport: '',
      cost:null
    });
  }

addDetail(): void {
    this.eventDetails.push(this.buildDetail());
    this.updateForm();
  }

  updateForm(){
    this.appService.triggerFormChange(this.eventForm);
  }
}

最终,子组件将订阅共享服务的formChangeEvent(),并如下所示重新构建表单。

import { Component, OnInit, Input, OnChanges, SimpleChanges } from '@angular/core';
import { FormGroup, FormArray } from '@angular/forms';
import { AppService } from '../app.service';

@Component({
  selector: 'child-component',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css'],
})

export class ChildComponent implements OnInit {
  eventDetails: FormArray;
  formInfo: FormGroup;
  constructor(
    private appService: AppService
  ) { }
  ngOnInit() {
    this.appService.formChangeEvent().subscribe(res => {
      console.log(res);
      this.formInfo = res;
      this.eventDetails = this.formInfo.get('eventDetails') as FormArray;
    });
  }

}

父组件(app.component.html)

<div class="container">
<div>Child Component 1
</div>
<hr>

<child-component></child-component>

<div>Child Component 2
</div>
<hr>

<child-component></child-component>
<button class="btn btn-outline-primary"
            type="button" style="margin-left:10px; font-size: 12px;"
            (click)="addDetail()">
      Add Details
    </button>

child.component.html

<form *ngIf="!!formInfo" [formGroup]="formInfo">
<ng-container formArrayName="eventDetails">
    <div *ngFor="let _ of eventDetails.controls; index as i">
        <div class="item row" [formGroupName]="i">
            <div class="col-sm-6">
                <div class="form-group">
                    <label for="eventName" class="col-form-label">Event Name</label>
                    <div>
                        <input type="text" class="form-control" id="eventName" formControlName="eventName">
</div>
                    </div>
                </div>
                <div class="col-sm-6">
                    <div class="form-group">
                        <label for="desc" class="col-form-label">Description</label>
                        <div>
                            <input type="text" class="form-control" id="desc" formControlName="desc">
</div>
                        </div>
                    </div>
                </div>
            </div>
</ng-container>