【问题标题】:Angular call child component method from parent component从父组件角度调用子组件方法
【发布时间】:2022-07-07 19:53:16
【问题描述】:

我有一个父组件,其中包含三个子组件实例。

child-product-detail.component.html

<form id="frmProduct" #frmProduct="ngForm" (ngSubmit)="onSave(frmProduct)">
   <ng-content select="[buttons-view]"></ng-content>
   <input type="text" id="txtProductName" name="txtProductName" [(ngModel)]="product.productName" />
</form>

child-product-detail.component.ts

onSave(form) {
    let isValid = this.validate(form);
    if (!isValid) return;
}

parent-product.compoment.html

<child-product-detail [product]="products[0]">
   <div buttons-view>
       <button type="button" class="btn" (click)="saveProduct(0)" >Save</button>                                    
   </div>
</child-product-detail>
<child-product-detail [product]="products[1]">
   <div buttons-view>
       <button type="button" class="btn" (click)="saveProduct(1)" >Save</button>                                    
   </div>
</child-product-detail>
<child-product-detail [product]="products[2]">
   <div buttons-view>
       <button type="button" class="btn" (click)="saveProduct(2)" >Save</button>                                    
   </div>
</child-product-detail>

parent-product.component.ts

saveProduct(productId) {
    let productToSave = this.products(productIndex);
    // Code required to call onSave method of child component
}

无论如何我可以调用子组件的onSave方法传递它的表单对象吗?

谢谢。

【问题讨论】:

  • 也许可以通过使用@ContentChildren 来做到这一点,但如果您发布了您想要完成的任务的完整描述并且您会好多以不同的方式解决了这个实际问题。您正在尝试做一些通常是反模式的事情,原因尚不清楚。

标签: angular typescript


【解决方案1】:

您可以使用ViewChildren 装饰器。

@ViewChildren(ChildProductDetailComponent)
childComponents: QueryList<ChildProductDetailComponent>;

saveProduct(productId) {
   this.childComponents.get(productIndex).onSave();
}

【讨论】:

  • 谢谢,如何将表单对象传递给 onSave() 方法?
【解决方案2】:

你可以使用事件发射器。

假设您的子组件具有这样的输出事件函数:

<app-product-stock (outputStockEvent)="outputStockEvent($event)"></app-product-stock>

那么这将是父函数中的函数:

public outputStockEvent(event){
    this.stock = event
  }

在子组件中:

    constructor(private fb: FormBuilder) {
        this.stockForm = this.fb.group({
          a: '',
          b: '',
          c:'',
        });
       }

.....
 

    ngOnInit(): void {
        this.stockForm.valueChanges.subscribe(data =>{
          this.outputStockEvent.emit(data)
        })
      }

如果您随后在 ParentComponent 中使用“保存”按钮, 您可以将值写入最终数组:

public save(){
  let finalObj ={ "stock":this.stock"}
}

【讨论】:

    猜你喜欢
    • 2019-04-16
    • 2016-10-30
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 2023-01-08
    • 1970-01-01
    • 2020-09-11
    相关资源
    最近更新 更多