[英]How to invoke a function in child component based on Boolean value passed from Parent component?
我正在顯示從子組件到 AppComponent(父)的按鈕。 每當單擊按鈕時,如果“ lastPage ”值設置為 true,我想調用“ showAlert() ”方法。 但這似乎不起作用。 附上一個stackblitz示例
這是從子組件調用 function 的正確方法嗎? 有不同的方法嗎?
app.component.html
<app-child [lastPage]="lastpage"></app-child>
app.component.ts
export class AppComponent {
lastpage = true;
name = 'Angular ' + VERSION.major;
}
child.component.html
<button>Click me for Alert</button>
child.component.ts
export class ChildComponent implements OnInit {
@Input() lastPage?: boolean
constructor() { }
ngOnInit() {
this.showAlert()
}
showAlert() {
if (this.lastPage) {
alert('Button Clicked from child');
}
}
}
您可以使用 ngOnChange 掛鈎來捕獲輸入更改以及可以在哪里調用您的方法在此處輸入鏈接描述
對組件中 Input() 的更改做出反應的正確方法是通過ngOnChanges()
生命周期。
ngOnChanges()
生命周期接受 SimpleChanges 類型的參數SimpleChanges
class 定義如下:
class SimpleChange {
constructor(previousValue: any, currentValue: any, firstChange: boolean)
previousValue: any
currentValue: any
firstChange: boolean
isFirstChange(): boolean
}
因此,您可以利用此屬性找出Input()
的 currentValue 是什么,並在您的代碼中采取相應的行動:
ngOnChanges(changes:SimpleChanges){
if(changes.lastPage.currentValue){
this.showAlert()
}
}
您可以在此頁面中找到更多信息: https://angular.io/api/core/OnChanges
app.component.ts
export class AppComponent {
lastpage = true; // true or false
}
child.component.html
<button (click)="showAlert()">Click me for Alert</button>
child.component.ts
export class ChildComponent implements OnInit {
@Input() lastPage?: boolean
constructor() { }
ngOnInit() { }
showAlert() {
if (this.lastPage == true) {
alert('Button Clicked from child');
}
}
}
您有幾個選項可以觸發 function。 您可以像其他人提到的那樣使用 OnChanges Hook,也可以使用 getter 和 setter。
但是,我認為您應該從父組件而不是子組件觸發警報。 子組件應該盡可能的愚蠢。
export class ChildComponent {
@Output() clicked = new EventEmitter<void>();
onClick() {
this.clicked.emit();
}
}
export class ParentComponent {
lastPage = true;
showAlertIfLastPage() {
if (this.lastPage) {
alert('Button Clicked from child');
}
}
}
<app-child (clicked)="showAlertIfLastPage()"></app-child>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.