[英]Angular - How to invoke function from parent to child component
我有這種情況:以這種方式構造的父組件:
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-content):
<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 子 function ...這可能嗎?
<app-parent>
<app-child>
</app-child>
</app-parent>
這是一個樣本; 我正在創建一個具有默認按鈕的模式:“取消”和“成功”。 在成功按鈕上,我需要調用一個聲明到 childrenComponent 中的 function。
這是 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>
app.component.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();
}
}
父組件.html
<div>
<ng-content></ng-content>
<button (click)="clickAction()">Click to say Hello!!!</button>
</div>
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.