Adjust the component's input value using a different component

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();
}

Answer №1

One approach is to utilize the onHide callback from a dialog in order to toggle a flag within the HomeComponent. This flag can then be passed to the UserComponent, where you can check if it is true (indicating that the dialog has been closed). Subsequently, perform your desired action and utilize an event emitter to notify the HomeComponent to reset the flag to false.

If you need to check the flag within the UserComponent, consider utilizing the ngOnChanges lifecycle hook.

Alternatively, you can use ViewChild inside the HomeComponent:

@ViewChild(UserComponent)
private userComponent: UserComponent;

Then, within the onHide method:

onHide() {
  // Reset inputs
  this.userComponent.name = '';
}

Answer №2

To ensure proper functionality, make sure to set up an event listener on your dialog element:

@Output()
private dismissEvent: EventEmitter<boolean> = new EventEmitter();

onDismiss() {
    dismissEvent.emit(true);
}

Then, in the parent component, you can listen for this event and trigger custom actions:

<custom-dialog (dismissEvent)="handleDismissal()" >
</custom-dialog>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I've noticed that the list item vanishes unexpectedly when utilizing Primeng drag-and-drop feature

Whenever I try to drag an item from one list to another in the Primeng picklist, the item disappears until it is dropped. <p-dialog [(visible)]="showMarker" (onHide)="hideDialogChild()" [contentStyle]="{'overflow':'visible'}" h ...

Tips for setting NgForm value within an Observable and verifying its successful implementation

Exploring the functionality of NgForm, I am testing to validate if the value of a form gets updated when the state of the store changes. @ViewChild('form') form: NgForm; ngOnInit() { this.subscription = this.store.select('shoppingList&apos ...

Easy way to transfer a property value from TypeScript file of one component to another

first-component.ts detailsList=[ { text: value, icon: image }, { text: value, icon: image } ] second-component.html <p>{{detailsList.text}}</p> Can this be easily achieved? ...

gyp ERROR: Npm encounters difficulty in obtaining a local issuer certificate

I recently did a fresh installation of Windows 10, keeping it clean except for adding cygwin to access Unix commands in the command prompt. During my attempt to install @angular/cli with the command npm install -g @angular/cli, I encountered an error afte ...

TypeScript compilation error - No overload is compatible with this call

Currently, I am working on a project using TypeScript alongside NodeJS and Express. this.app.listen(port, (err: any) => { if (err) { console.log("err", err) } else { console.log(`Server is listing on port ${port}`); } }); The co ...

Deactivate input fields in FormArray using a checkbox

I am currently working on a multi-step form that includes a FormArray for schools in the third step. Within this FormArray, there is an input field called 'endDate' where users can check a checkbox labeled 'En Curso' (in progress) if th ...

Storing data efficiently with Angular 2's local storage service

I am attempting to create a ToDoList using localstorage within a service. add.component.ts export class AddComponent implements OnInit { item: Item[]; constructor( private router: Router, private itemService: ItemService) { } ...

When I include formControlName in Angular, the select dropdown loses its default value

I seem to be facing an issue with my select element. When I include the formControlName, the placeholder "-- Select Event Type --" no longer appears (even though it is still selected in the dropdown). If I remove it, the placeholder displays but the valida ...

Angular relative routes are failing to function

I am currently working on implementing a feature module in my project and following the documentation provided. My crisis-routing.module file looks like this: import { NgModule } from '@angular/core'; import { Routes, RouterModule } from ' ...

I can't seem to catch my Zod error, even though 'express-async-errors' is already installed. What could be causing this issue?

I've been working on developing an API, but I'm facing issues with setting up a global error controller using Zod. It seems that the global error handler is not being called even though I'm using express-async-errors. Below is my error mana ...

Why do variables in an HTML file fail to update after being navigated within onAuthStateChanged?

Currently, I am working with Ionic 5 and Firebase. Everything is running smoothly until I implemented the onAuthStateChanged function to persist login for authenticated users. Here is the code snippet: this.ngFireAuth.onAuthStateChanged((user) => { ...

Two lines in ChartJS with distinct fill gradients for each

I am facing an issue with ChartJS version 2.6 in my Ionic 3/Angular 4 app. I have set up a line chart config with 2 datasets, but I am struggling to apply individual fill gradients to each line. What I am aiming for is something like this: https://i.stac ...

Learn the steps for implementing i18n-x in Angular 2 to localize constant property values

I am currently working on localizing my Angular2 application using the i18n-x form from here. It has been successful for attributes like so: <p-dialog i18n-header header="User Details"></p-dialog> The result is: <trans-unit id="fe871da89f ...

What potential issue could result in a property length of null error while working with a Material Data Table?

I'm experiencing a similar issue as the one discussed in this post, but none of the suggestions there have resolved my problem, and my scenario has some differences. In my case, a parent component is assigning an array to a child component's inp ...

Ensure that missing types are included in a union type following a boolean evaluation

When working with typescript, the following code will be typed correctly: let v: number | null | undefined; if(v === null || v === undefined) return; // v is now recognized as a `number` const v2 = v + 2; However, if we decide to streamline this process ...

Different Ways to Modify Data with the Change Event in Angular 8

How can I dynamically change data using the (change) event? I'm attempting to alter the gallery items based on a matching value. By default, I want to display all gallery items. public items = [{ value: 'All', name: 'All Item ...

Navigating SSL certificate prompts in Protractor

Our programs utilize SSL certificates and we are unable to bypass Chrome's prompt for selecting a certificate. We would be satisfied with simply choosing the one certificate needed. Attempts have been made using this code: capabilities: { browser ...

Exploring the return type of the `within` function in TypeScript Library

I have helpers set up for my React tests using the testing library: const getSomething = (name: string, container: Screen | any = screen) { return container.getByRole('someRole', { name: name }) } The container can be either the default screen ...

Issue with Angular: Unable to properly sort data while modifying queryParams

Within the component.ts file: export class TabsComponent implements OnInit { constructor( private store$: Store<UsersState>, private router: ActivatedRoute ) {} ngOnInit(): void { this.onFilterByIncome(); this.router.queryParam ...

Service that spans the entire application without relying on a service that is also used throughout the application

In continuation of my previous question, I am facing an issue with the No provider for ObservableDataService. I have an application-wide service named UploadedTemplatesService which must be a singleton. This service has one dependency - ObservableDataServ ...