繁体   English   中英

如何根据从父组件传递的 Boolean 值在子组件中调用 function?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM