Let's talk about two components in this scenario - HomeComponent and UserComponent. The UserComponent is a child of the HomeComponent and has the following structure:
UserComponent.html:
<form [formGroup]="form">
<div style="display:block">
<label style="display:block">Search:
<input #filterString formControlName="filterString" type="text" id="testInput" class="ui-corner-all">
</label>
</div>
<p-dataTable>
//Primeng datatable...
</p-dataTable>
UserComponent.ts:
@Component({
selector: 'user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class ProjektAuswahlComponent implements OnInit {
form = new FormGroup({
filterString: new FormControl('', Validators.required)
})
constructor(/*possible services*/) {
}
ngOnInit() {
//do something...
}
get filterString() { return this.form.get('filterString') };
clearInput(){
this.filterString.setValue('');
}
}
Now, let's take a look at the HomeComponent layout -->
HomeComponent.html:
<!--
some other stuff like buttons and paragraphs...
<button id="userBtn" class="someCssStyles">OpenUser</button>
-->
<p-dialog id="homeDialog" styleClass="random" closeOnEscape="true" [contentStyle]="{'overflow':'auto'}"
[(visible)]="display" modal="modal" width="650" height="auto" [responsive]="true" [resizable]="true" (onShow)="showDialog()" (onHide)="hideDialog()" >
<p-header>
<div style="text-align: center;">My First Header</div>
</p-header>
<user></user>
</p-dialog>
HomeComponent.ts:
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
//Show / hide Dialog
public display: boolean = false;
constructor(/*possible webservices service*/){}
ngOnInit(){
/*load data from service class*/
}
showDialog(){
this.display = true;
}
hideDialog(){
this.display = false;
}
When you load the website, the HomeComponent will be visible with buttons displayed and a hidden Primeng dialog. Clicking on the "OpenUser" button will open the dialog which contains the User template inside. Inside the User template, there is an input field used to filter a datatable. The main objective is to clear the input fields value when the dialog closes. The dialog has a callback event called onHide which should handle this task.
The question now arises - how can we clear the UserComponent's input value from the HomeComponent when the dialog closes?
I attempted to create a UserComponent instance within the HomeComponent and call a function to clear the value, but it didn't work as expected. Although the method was executed, the view did not update. Here is a snippet of what I tried:
HomeComponent.ts:
//imports
//@Component
//etc.
constructor(private userComponent: UserComponent){
userComponent = new UserComponent();
}
hideDialog(){
this.userComponent.clearInput();
}