Issue
I am displaying a button from child component to AppComponent(parent). Whenever the button is clicked I would like to invoke the 'showAlert()' method if 'lastPage' value is set to true. But it doesn't seem to work. Attached a stackblitz example
Is this a correct way to invoke a function from the child component? is there a different way to do it?
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');
}
}
}
Solution
You have a few options for triggering that function. You can use the OnChanges Hook as others mentioned or you can use a getter and a setter.
However, I think you should trigger the alert from the parent component rather than the child. The child component should be as dumb as possible.
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>
Answered By - ionut-t
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.