Angular-如何从父组件调用函数到子组件



我有这样的情况:以这种方式构建的父组件:

import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}

使用此html(父级具有ng内容(:

<div>
<ng-content></ng-content>
<button>Click to say Hello!!!</button>
</div>

和一个类似的子组件:

import { Component, OnInit } from "@angular/core";
@Component({
selector: "app-child",
templateUrl: "./child.component.html",
styleUrls: ["./child.component.css"]
})
export class ChildComponent implements OnInit {
onSubmit() {
alert("hello");
}
constructor() {}
ngOnInit() {}
}

用这个html:

<div>I'm child component</div>

从父组件中,我想单击内部按钮来调用onSubmit子函数。。。这可能吗?

<app-parent>
<app-child>
</app-child>
</app-parent>

这是一个样本;我正在创建一个具有默认按钮的模态:;CANCEL";以及";成功";。在成功按钮上,我需要调用childrenComponent中声明的一个函数。

这是stackblitz示例:https://stackblitz.com/edit/angular-ivy-vuctg4

您可以访问类似的

app.component.html

<hello name="{{ name }}"></hello>
<app-parent (clickActionCB)="clickActionCB($event)">
<app-child></app-child>
</app-parent>

应用程序组件.ts

import { Component, VERSION, ViewChild } from "@angular/core";
import { ChildComponent } from "./child/child.component";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
name = "Angular " + VERSION.major;
@ViewChild(ChildComponent) childRef: ChildComponent;
clickActionCB(eventData) {
this.childRef.onSubmit() ;
}
}

父组件.ts

import { Component, EventEmitter, OnInit, Output } from "@angular/core";
@Component({
selector: "app-parent",
templateUrl: "./parent.component.html",
styleUrls: ["./parent.component.css"]
})
export class ParentComponent implements OnInit {
constructor() {}
ngOnInit() {}
@Output() clickActionCB = new EventEmitter<string>();
clickAction() {
this.clickActionCB.emit();
}
}

parent.component.html

<div>
<ng-content></ng-content>
<button (click)="clickAction()">Click to say Hello!!!</button>
</div>

Live stackblitz URL

child.component.ts

import { Component, OnInit } from "@angular/core";
@Component({
selector: "app-child",
template: `
<div>I'm child component</div>
`
})
export class ChildComponent implements OnInit {
onSubmit() {
alert("hello");
}
constructor() {}
ngOnInit() {}
}

父组件.ts

import { ChildComponent } from "../child/child.component";
@Component({
selector: "app-parent",
template: `
<div>
<ng-content></ng-content>
<button (click)="onClick()">Click to say Hello!!!</button>
</div>
`
})
export class ParentComponent implements OnInit {
@ContentChild(ChildComponent) childRef: ChildComponent;
constructor() {}
ngOnInit() {}
onClick() {
this.childRef.onSubmit();
}
}

https://stackblitz.com/edit/angular-ivy-mteusj?file=src%2Fapp%2Fparent%2Fparent.component.ts

最新更新