Angular从父组件调用子组件方法



我有一个父组件,里面有三个子组件的实例。

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子组件通过表单对象的方法呢?

谢谢。

您可以使用ViewChildren装饰器

@ViewChildren(ChildProductDetailComponent)
childComponents: QueryList<ChildProductDetailComponent>;
saveProduct(productId) {
this.childComponents.get(productIndex).onSave();
}

你可以使用事件发射器

假设你的子组件有一个这样的输出事件函数:

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

如果使用"Save"按钮,您可以将值写入最终数组:

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

是的,您可以使用@Output指令来发出自定义事件.

例如:

child-product-detail.component.ts

import { Component, EventEmitter, Output } from '@angular/core';
export class ChildProductDetailComponent {
@Output() yourEventEmitter = new EventEmitter<any>();
onSave(form) {
let isValid = this.validate(form);
if (isValid) {
this.yourEventEmitter.emit(form)
};
}
当onSave()被执行时,它会发出yourEventEmitter

parent-product.compoment.html

<child-product-detail (yourEventEmitter)="saveProduct($event)">
<button type="button" class="btn" (click)="onSave(0)" >Save</button>
</child-product-detail>

父组件获得事件并运行函数saveProduct()通过$event接收表单。

parent-product.component.ts

saveProduct(productId) {
// the productId is the form from the child component
}

你可以了解更多关于它https://angular.io/api/core/EventEmitter

最新更新