I have this form that is almost ready. Now I only have to make a modal window with content and it should pop open with click on a button which is inside of a child component. Modal, on the other hand, is a part of a parent component. I need to communicate them with each other in order to inform the parent, that the button was clicked and that now it's time to open a modal. I emit a boolean event, which is equal to the state of a clicked button, but I don't get any reaction from the parent, although I have a property bindable from outside ( @Input()
) How can I achieve such a task? Where am I mistaken?
Child component method
onReset() {
this.formResetClicked = !this.formResetClicked;
this.formReseted.emit(this.formResetClicked); }
Parent's HTML
<div class="container">
<div class="wrapper">
<div class="slider">
<app-form-slider class="slider-app"></app-form-slider>
</div>
<div class="form" (formReseted)="clickedState = $event">
<router-outlet></router-outlet>
</div>
<div class="modal" [ngStyle]="{display: clickedState ? 'block' : 'none'}">
<div class="modal__content">
<div class="modal__content--header">
<span>×</span>
<p>WARNING!</p>
</div>
<div class="modal__content--text">
<p>If you click 'continue' the all information will be deleted. <br>Close this window if you don't want this to happen.</p>
</div>
<div class="modal__content--button">
<button>Continue</button>
</div>
</div>
</div>
</div>
</div>
Property of a parrent
export class AppComponent {
title = 'AwesomeFormTask';
@Input() clickedState: boolean;
}
Do not need to use @Input()
. You can call child component to parent component using @Output()
and EventEmitter
as follows.
child.component.ts
@Output() formReseted = new EventEmitter<boolean>();
formResetClicked: boolean = false;
onReset() {
this.formResetClicked = !this.formResetClicked;
this.formReseted.emit(this.formResetClicked);
}
Listen to formReseted
event
from the parent as follows.
parent.component.html
<child (formReseted)="testShowHide($event)"></child>
<p *ngIf="show">Showing the Modal</p>
parent.component.ts
show: boolean = false;
testShowHide(show) {
this.show = show;
}
There is a problem with how you handled the event. @Input
will create a bindable property on the component selector. So don't use @Input
.
Like the following
childComponent.ts
export class ChildComponent {
@Output() formReseted = new EventEmitter<boolean>();
formResetClicked = false;
public onReset() {
this.formResetClicked = !this.formResetClicked;
this.formReseted.emit(this.formResetClicked);
}
}
parentComponent.html
<app-child (formReseted)="onFormReset($event)"></app-child>
parentComponent.ts
onFormReset(isFormResetClicked) {
console.log(isFormResetClicked)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.