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

Detecting file changes in ExpressJS after writing data to a file.This

I'm facing an issue with my endpoints. One endpoint is responsible for writing JSON data to a static file, while another endpoint is supposed to retrieve and send that data. The problem arises when I make changes to the file but the endpoint still sen ...

Can you provide guidance on how to use Javascript to submit a form specifically when the input name is labeled as "submit"?

Query: How can I use Javascript to submit a form when one of the form inputs is named submit? Scenario: I need to send users to another page using a hidden HTML form. Unfortunately, I cannot modify the names of the inputs in this form because it needs to ...

In jQuery, a dropdown selection can be filled with multiple textboxes sharing the same class

I'm experimenting with the idea of using multiple textboxes with the same class filled with different dropdown options that also have the same class. However, I am encountering some issues. When I click on a dropdown option, it changes the value in a ...

"Exploring the Art of Showcasing Duplicate Image Count from User Input in an

I need to showcase multiple duplicates of 2 different images on a webpage. Users are asked for the duplication speed, which I have already implemented, and also how many copies of each image they want. function show_image() { var img = document.create ...

Looking to bring in a non-ES6 library into VueJS without using export statements

Currently, I am faced with an interesting challenge. For a forthcoming VueJS project, we must utilize a library that is quite outdated but there is simply not enough time to redevelop it. The library is essentially a JavaScript file which consists of num ...

Using nodeJS's util module to format and pass an array

I've been using util.format to format strings like this: util.format('My name is %s %s', ['John', 'Smith']); However, the second parameter being an array ['John', 'Smith'] is causing issues because m ...

Is it possible to modify the appearance or behavior of a button in a React application based on its current state?

I'm looking to customize the color of a button based on different states. For example, if the state is active, the button should appear in red; otherwise it should be blue. Can anyone suggest how this can be achieved in React? Furthermore, I would als ...

loop through an intricate JSON schema using Angular 5

I've been trying to figure out how to iterate a complex JSON in Angular 5. I came across the pipe concept, but it doesn't seem to work with JSON data like the one below. I'm trying to create an expandable table using this type of data, but I ...

Steps for eliminating the chat value from an array tab in React

tabs: [ '/home', '/about', '/chat' ]; <ResponsiveNav ppearance="subtle" justified removable moreText={<Icon icon="more" />} moreProps={{ noCar ...

Manipulate values within an array when a checkbox is selected or deselected

I am developing an Angular application where I have created a checkbox that captures the change event and adds the checked value to an array. The issue I am facing is that even if the checkbox is unchecked, the object is still being added to the array. D ...

vuex: The decision between using $store.commit and directly calling the function

Recently, I discovered an interesting technique where store mutation functions can be passed into HTML events. Here's an example: //In the template <input name="the_field" :value="the_field" @input="updateField"/> // In the component methods ...

AngularJS Banner: Displaying Current Calendar Week and Increasing by 10 Days

I'm brand new to Angular and currently encountering some issues. Here's what I'm trying to create: I need to display the current Date: yyyy-MM-ss (Functional) I want to show the current Calendar Week: yyyy-Www (Not Working) When a butto ...

Showing the computation outcome on the identical page

I have implemented a table within my PHP code. In the second column of this table, it typically displays "---". However, once I click the submit button, the same page should now display the calculated result. Here is an example: <table> <tr>& ...

Retrieve a specific value from an array of objects by searching for a particular object's value

Here is an example of an array of objects I am working with: $scope.SACCodes = [ {'code':'023', 'description':'Spread FTGs', 'group':'footings'}, {'code':'024', ' ...

Tracking the advancement of synchronous XMLHttpRequest requests

Within the client-side environment, there exists a File-Dropzone utilizing the HTML5 File-API which allows users to drop multiple files for uploading to the server. Each file triggers the creation of a new XMLHttpRequest Object that asynchronously transfer ...

Obtain date and currency formatting preferences

How can I retrieve the user's preferences for date and currency formats using JavaScript? ...

Incorporate data from a CSV file into an HTML table on the fly with JavaScript/jQuery

I have a CSV file that is generated dynamically by another vendor and I need to display it in an HTML table on my website. The challenge is that I must manipulate the data from the CSV to show corrected values in the table, only displaying products and not ...

"The Material-UI ListItem component acts as a link, updating the URL but failing to render the expected

Seeking help for the first time on this platform because I am completely perplexed. I'm working on coding a navbar for my school project website using Material-UI's List component within the Appbar component. However, I have encountered two issu ...

Unbinding or undoing an 'onclick' event when another 'onclick' event is triggered

I am facing an issue where clicking on elements with 'onclick' functions works as expected, but when I click on a different element with another 'onclick' function, the first one remains active. What I actually want is for the previous ...

Leveraging React Hooks' useEffect to trigger a prop callback function defined with useCallback

Currently, I am working on developing a versatile infinite scrolling feature using React Hooks along with the ResearchGate React Intersection Observer. The main concept revolves around a parent passing down a mapped JSX array of data and a callback functio ...