When parent components reference child components, their values appear as null

I'm dealing with both a parent component and a child component in my project. The child component contains a form that should be saved if the user makes changes and then tries to navigate away by clicking on a link within the parent component.

Parent Component

@Component({
  selector: 'parent',
  templateUrl: './parent.html',
  providers: [MessageService]    
})
export class ParentComponent {
  @ViewChild('child') child: ChildComponent;
  message: any;

The ChildComponent is equipped with a form containing a considerable amount of data. Additionally, it contains an object named user that must have the appropriate permissions in order to save the form.

Child Component

 save() {
   if (this.user.role <= 2) postFormDataToDb();

Within the parent component, when a navigation link is clicked to go away, the following method is invoked:

this.child.save();

An error is encountered stating that this.child is null. It appears that the ChildComponent is being created as a new instance with empty values, rather than as the existing one. Despite this, the form seems to exist in the DOM as one of the fields can still be inspected.

I've attempted various methods to address this issue, but all lead to a null error. I've experimented with using a shared MessageService and subscribing to its messages.

this.subManager = this.messageService.getMessage().subscribe(message => {
  this.message = message;
  console.log("message=",message);
});
this.sendMessage('save');

However, the message doesn't reach the button (no content is displayed in the div).

<div *ngIf="message" (click)="saveUsers()">{{message.text}}</div>

I've also attempted to specifically target the #saveBtn from the child form using ViewChild.

@ViewChild('saveBtn') saveBtn: ElementRef;

And then tried to trigger a click event using the following code in the parent component:

this.saveBtn.nativeElement.click();

However, an error is reported stating that this.saveBtn is null.

The link provided appears to be related to a similar question, but the solutions involve *ngIf directives which I'm not currently utilizing, with the exception of displaying the message.

What am I overlooking in this scenario?

Answer №1

After trying different approaches, I was able to make it function by incorporating traditional JavaScript methods. This involved assigning the id="saveBtn" to the button, and then triggering a click event using the code snippet:

document.getElementById('saveBtn').click();

This modification was made in the parent.ts file.

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

Building a Secure User Service in Angular

Struggling to develop a security service for my Angular app, I encountered an issue with repetitive calls to the back-end API (which determines user permissions). Ideally, I want this call to happen once and other requests to piggy-back on that initial req ...

Exploring the World of Angular2 Interfaces

Just starting out with Angular 2 and I'm wondering if anyone can provide a clear explanation of the interface concept in Angular 2. It would be really helpful for me if you could explain it with a working example. Additionally, I would appreciate som ...

Test the HTML element using ngIf async call in Angular 2 with Jasmine unit testing

As I work on writing unit tests for an HTML div with a condition using *ngIf, I come across a specific scenario. <div *ngIf="clientSearchResults$ | async as searchResults" class = 'fgf' #datalist id="mydata" > <app-client-list id=" ...

Accessing the constants and state of child components within a parent component in React

I've created a MUI TAB component that looks like this <Box sx={{ width: "100%" }}> <Box sx={{ borderBottom: 1, borderColor: "divider" }}> <Tabs value={value} onChange={handleChange} aria-label ...

Different methods to prompt TypeScript to deduce the type

Consider the following code snippet: function Foo(num: number) { switch (num) { case 0: return { type: "Quz", str: 'string', } as const; case 1: return { type: "Bar", 1: 'value' } as const; default: thr ...

The quantity of elements remains constant in the EventEmitter

The Grid component is structured as follows: export class GridComponent { @Output('modelChanged') modelChangedEmitter = new EventEmitter(); private valueChanged(newValue: any, item: Object, prop: string) { item[prop] = newValue; ...

Encounter a net::ERR_EMPTY_RESPONSE error while trying to deploy an Angular application on a production server

I have successfully developed an Angular App on my local machine and now I am facing challenges while trying to deploy it on a Windows production server. I have set up Apache to serve the App along with the Rest Service API. Accessing the App through the ...

Steer clear of type assertion in your codebase when utilizing useSelector alongside Redux, Immutable.js, and TypeScript

Currently, I am working with a combination of Redux, Immutable.js, and TypeScript. I am facing challenges in obtaining proper types from the useSelector hook, which is leading me to use type assertions. I acknowledge that this is not the best practice and ...

The Next.js template generated using "npx create-react-app ..." is unable to start on Netlify

My project consists solely of the "npx create-react-app ..." output. To recreate it, simply run "npx create-react-app [project name]" in your terminal, replacing [project name] with your desired project name. Attempting to deploy it on Netlify Sites like ...

The ASP .Net Core 3.1 Angular template is malfunctioning

https://i.sstatic.net/T3hFx.pngAfter creating a new Web Project using the .Net Core with Angular template in Visual Studio 2019, I encountered an error when trying to build the solution. The error message stated: An unhandled exception occurred while proce ...

Angular showcases the presence of a signed-in user at page load, disregarding the absence of

Currently, I am following a course where I have implemented a simple login form inside the navigation bar: <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-primary"> <div class="container"> ...

Optimizing row performance for Angular grids in the Chrome browser

When creating a component that includes a table with numerous rows, everything works well with small amounts of data. However, once the item count reaches 2000 or more, it starts lagging. Scrolling and animations become sluggish. Even after trying to impl ...

Guide on how to refresh a child component in Angular after a function yields a fresh value?

Two main elements are at play here: Parent and Child. parent.ts class Parent { state = 0; ... }; parent.html <child [state]='state'> </child> Whenever the state in Parent is modified, the child component reflects the change ...

What is the process for creating a new element and utilizing its reference to add child elements in React?

I've been struggling to create an HTML element in a parent component in React, and then access that component's div from a child component in order to add new elements to it. Despite multiple attempts, I can't seem to resolve the issue of p ...

Acquired this as empty

I encountered a strange error message saying "this is null" and I can't figure out what the issue is. Here is my demo on Stackblitz.com with an example code for your reference. Component ngOnInit() { this.getCurrentLocation(); } getCurrentL ...

Update an API call to switch from promises to observables, implementing axios

Recently, I have been experimenting with using rxjs for API requests in a React application and this is the approach that I have come up with. What are your thoughts on this method? Are there any best practices that you would recommend following? If you ...

Troubleshooting Problems with Linking Components to app.component.html in Angular

I have created a few components, but I am having trouble getting them to work properly. When running 'ng serve', I encounter errors. If 'app-test' is supposed to be an Angular component, make sure it is included in the '@Compone ...

Utilize Angular for the front-end user interface and Asp.Net for the backend within the same Azure App

I am facing a challenge with deploying Angular and Asp.Net together on the same app service in Azure. Despite defining the Physical Path for the Angular project, it is not visible on the website and instead shows an error. Interestingly, when I deploy only ...

Diving into Angular Typescript: Understanding the [object Object] in HTML

One of my todos requires the following input: todo.ts: import { TodoTag } from "./todo-tag-custom"; export class Todo { ... tags: TodoTag[]; } todo.html <tr *ngFor="let todo of todosFiltered()"> <td>{{todo.tags | json ...

Testing network connection using alert feature in Ionic 2

Looking to verify network connectivity with an alert in Ionic 2. While this guide was helpful, it is quite outdated now and Ionic 2 syntax has evolved. Despite modifying the Alert component as suggested in the comments, I'm still encountering errors. ...