Angular - 从 parent class 调用 child 组件函数

Angular - Call child component function from parent class

我有一个 parents class 集成了两个 child 模板(3 个单独的表单详细信息合二为一)。 示例表格格式如下:

Parent表格

添加 Parent 表格。

在上面的示例中,我能够使用 formarray 和 formbuilder 成功地复制表单元素。但是,当我单击“添加 Child A 详细信息”时,它应该复制 Child B 表单下的表单元素,但在当前设计中,它在 child B.[=16= 之前被复制]

为了满足上述要求,我尝试在 parent 表单中添加 child 功能的“添加”按钮,并尝试与 child [=56] 进行交互=] 通过使用输入装饰器。但是我不确定如何将点击事件发送到 child 表单以触发从 parents class.[=16 添加到 child 的功能=]

Parent形式:

<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>

Child答:

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 的新手,请帮忙,如果有任何其他方式来实现要求而不是输入装饰器,请告诉我。

谢谢!

我们可以通过多种方式在angular中实现组件交互。

  1. 使用@Input[属性绑定],@Output(事件发射)
  2. 使用 Rxjs Observable/Subjects
  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();
  }
}

父组件(App 组件)将更新的表单提供给共享服务,如下所示。

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>