The struggle of accessing child components using ViewChild in Angular

I am facing an issue with a dialog box that is supposed to display a child component separately. Below is the code for the child component:

@Component({
  selector: 'userEdit',
  templateUrl: './edituser.component.html',
  styleUrls: ['./edituser.component.css']
})
export class EditUserComponent implements OnInit {
  public theName: string;
  public theAddress: string;

  constructor() {
    this.theName = '';
    this.theAddress = '';
  }

  ngOnInit() {
  }

}

Here is the code and template for the dialog box:

@Component({
  selector: 'app-userdialog',
  templateUrl: './userdialog.component.html',
  styleUrls: ['./userdialog.component.css']
})
export class UserDialogComponent implements OnInit {
  @ViewChild('userEdit', {static: false})
  userEdit: EditUserComponent;

  constructor(
    public dlgRef: MatDialogRef<UserDialogComponent>,
   @Inject(MAT_DIALOG_DATA) public theData: UsrStuff) { }

  ngOnInit() {
  }

  ngAfterViewInit() {
    console.log('Name: ' + this.userEdit.theName);
  }

  addUser() {
  // TODO: implement adding a user
 }

  closeBox() {
    this.dlgRef.close();
  }
}

Additionally, the following code snippet is used in the template:

<div id="attribdlg">
    <h3>Add New User</h3>
    <userEdit theName="" theAddress=""></userEdit>
    <mat-dialog-actions>
        <button mat-raised-button color="primary" (click)="addUser()">Add User</button>
        <button mat-raised-button color="primary" (click)="closeBox()">Done</button>
    </mat-dialog-actions>
</div>

Despite following the documentation and examples, I encounter an error when trying to access the value of theName property in the child component's ngAfterViewInit() function. The error message states:

null: TypeError: Cannot read property 'theName' of undefined

It seems that there might be some initialization process missing for the child component. How can I ensure that the child component and its properties are accessible within my dialog?

Answer №1

Here are two different approaches you can take:

  1. Add an id to the desired component and use ViewChild():

TypeScript:

@ViewChild('userEdit', {static: false})

HTML:

<userEdit #userEdit theName="" theAddress=""></userEdit>
  1. Alternatively, select by directive or component:

TypeScript:

@import { EditUserComponent } from '...';

@ViewChild(EditUserComponent, {static: false})

HTML:

<userEdit theName="" theAddress=""></userEdit>
  • It is recommended to use the app prefix for the component's selector.
@Component({
   ...
      selector: 'app-user-edit',
   ...
})

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

Yarn Plug'n'Play was unable to locate the module during the next build

Currently, I am in the process of developing a Next.js project with yarn's Plug'n'Play feature. In this project, I have created several pages and added various packages, including mathjs: '^10.3.0' to assist me in parsing user inpu ...

Tips for resolving the UNABLE_TO_GET_ISSUER_CERT_LOCALLY issue while attempting to install Sentry using npm or curl

https://i.stack.imgur.com/G8hfZ.png curl -sL -k https://sentry.io/get-cli/ | bash Even though I've specified not to verify the certificate with -k, I'm still facing issues trying to install it. The script is supposed to automatically install sen ...

Struggling to locate the correct setup for .babel and react-hot-loader

I am currently utilizing babel 7. In their documentation, they specify that the new naming convention for plugins should include the @babel/ prefix. The recommended React-hot-loader babelrc configuration is as follows: { "plugins": ["react-hot-loader/ ...

Node.js Axios Returns Bad Request with Status Code 400

I am currently facing an issue while trying to send the results of a nodejs query to an endpoint. Interestingly, I receive a successful response when using Postman with the correct parameters, but encounter errors when attempting to use axios. data: ' ...

The directive binding value is accurate, however it is failing to return a true result

The behavior of a custom directive is puzzling me. When I directly pass in a value, it works fine. However, if I bind the value to a variable, it doesn't work as expected. Interestingly, when I use console.log to show the value, it appears to be corre ...

Displaying AJAX Confirmation in a Popup Window

My form is set up to insert data into a database via an AJAX request. Upon successful insertion, the "rentinsert.php" will display a success message on the page that reads "Your order has been placed". However, I would like this success message to appear i ...

Navigating through the img src using JavaScript

Currently, I am working on a task that involves the following code snippet: <input type="file" id="uploadImage" name="image" /> <input type="submit" id="ImageName" name="submit" value="Submit"> My goal is to have the path of the selected imag ...

Determine if a cell is editable within the `renderEditCell` function by using MUI

I am working with a MUI data grid that contains different cell types. I am currently seeking a way to implement user permission-based editing for cells in the grid. However, I only want the permission testing to occur when a user attempts to edit a cell, r ...

Setting a custom background image in a Bootstrap modal

When users visit my website, I want to enhance their experience by using a background image in my bootstrap modal. Despite several attempts, I have been unable to successfully set a background image in the modal. Can anyone provide guidance on this matter? ...

What is the best method for converting IDs into objects within ng-options in Angular?

Is there a way to dynamically use an array of IDs as the source of my ng-option directive inside of select? Instead of creating an array of objects with corresponding IDs, I am wondering if there is a method to set a function as the source of ng-option. ...

The functionality of using multiple inputs with Google Places API is not functioning as expected

Having trouble with the Google Place API. I am unable to set up 2 input fields with autocomplete. The first input is populated from a payload received from the backend, while the second input is within a Bootstrap modal. I have tried various solutions fou ...

Automatically log into Google using Angular with Angularx-Social-Login

Utilizing Google sign-in and Angularx-Social-Login to authenticate users has been successful for me. However, I am facing an issue where users have to log in again whenever they reload the page or open a new tab, despite setting autologin: true. I have imp ...

In socket.io, the event occurs twice in a row

I am encountering an issue with my socket.io nodejs cluster setup in my project where the same event is triggered twice. Despite trying different versions of Socket.io, the problem persists and two instances of the same event are being emitted. The current ...

Encountering multiple error messages from Protractor @types

Lately, I've been using the Angular2 Webpack Starter created by AngularClass and I've started encountering some perplexing errors with Protractor. When trying to build, these errors pop up: Module 'webdriver' has no exported member &ap ...

Create new instances of Backbone Models using an existing Backbone Model as a template

Within my app, I am planning to include a configuration file called config.json as a Backbone Model. Here is an example of how it will be loaded: var Config = Backbone.Model.extend({ defaults: { base: '' }, url: 'config. ...

How can you store form field validation rules (for example, firstname.dirty) in an array within TypeScript in Angular?

How do I save form field validation rules in an array? What should replace /'''''HERE'''''/ with? formfields: Array<Object> = [ {label: "Employer:", control: "employer", val ...

Utilizing d3 Charts in Angular 4 Framework

I need assistance with integrating a bar chart in an Angular 4 project, which includes HTML and TypeScript files as components. Can someone please provide guidance on this? The bar chart should show the increase in the number of employees each month, star ...

The "require" keyword cannot be used in a Node-RED Function node

When working with a Node-RED Function Node, the first line I include is: var moment = require('moment-timezone'); I'm attempting to create a timezone accurate date/time stamp for sensor data. However, when this node runs, I encounter the fo ...

Verifying numerous route paths using Vue's dynamic binding (v-bind)

Currently, I am assigning a class to an li element depending on the route path using this code snippet: <li v-bind:class="{ 'current': $route.path == '/services' }"><nuxt-link to="/services">Services</ ...

Understanding the concept of a "class variable" in Typescript when referring to a variable that belongs to another class

When we declare a variable at the class level and assign it the type of another class, such as in the following code: let greeter: Greeter; //line 1 greeter = new Greeter("world"); What is contained within 'greeter' on line 1? ...