Error: When using @ViewChild, it is not possible to access the property 'nativeElement' if it is undefined

Currently, I am working on a project using Angular-7. I have been trying to access elements directly from the TypeScript file by utilizing @ViewChild, but encountered an error message. The code snippet in question is:

@ViewChild('serverContentInput', { read: true, static: true }) serverContentInput: ElementRef;
and it seems that it is not able to Access the Template & DOM with @ViewChild

Error:

ERROR TypeError: Cannot read property 'nativeElement' of undefined
    at CockpitComponent.onAddServer (cockpit.component.ts:24)
    at Object.eval [as handleEvent] (CockpitComponent.html:11)
    at handleEvent (core.js:34777)
    at callWithDebugContext (core.js:36395)
    at Object.debugHandleEvent [as handleEvent] (core.js:36031)
    at dispatchEvent (core.js:22519)
    at core.js:33709
    at HTMLButtonElement.<anonymous> (platform-browser.js:1789)
    at ZoneDelegate.invokeTask (zone-evergreen.js:391)
    at Object.onInvokeTask (core.js:30873)

cockpit.component.ts

import { Component, OnInit, EventEmitter, Output, ViewChild, ElementRef, Directive } from '@angular/core';

@Component({
  selector: 'app-cockpit',
  templateUrl: './cockpit.component.html',
  styleUrls: ['./cockpit.component.css']
})
export class CockpitComponent implements OnInit {
  @Output() serverCreated = new EventEmitter<{ serverName: string, serverContent: string }>();
  @Output('bpCreated') blueprintCreated = new EventEmitter<{ serverName: string, serverContent: string }>();

  // newServerName = '';
  // newServerContent = '';
  @ViewChild('serverContentInput', { read: true, static: false }) serverContentInput: ElementRef;

  constructor() { }

  ngOnInit() {
  }

  onAddServer(nameInput: HTMLInputElement) {
    this.serverCreated.emit({
      serverName: nameInput.value,
      serverContent: this.serverContentInput.nativeElement.value
    });
  }

  onAddBlueprint(nameInput: HTMLInputElement) {
    this.blueprintCreated.emit({
      serverName: nameInput.value,
      serverContent: this.serverContentInput.nativeElement.value
    });
  }
}

cockpit.component.html

<div class="row">
  <div class="col-xs-12">
    <p>Add new servers or blueprint !</p>
    <label>Server Name</label>
    <!-- <input type="text" class="form-control" [(ngModel)]="newServerName" /> -->
    <input type="text" class="form-control" #serverNameInput />  <!-- Local Reference -->
    <label>Server Content</label>
    <!-- <input type="text" class="form-control" [(ngModel)]="newServerContent" /> -->
    <input type="text" class="form-control" #serverContentInput  />
    <br>
    <button class="btn btn-primary" (click)="onAddServer(serverNameInput)">Add Server</button>
    <button class="btn btn-primary" (click)="onAddBlueprint(serverNameInput)">Add Server Blueprint</button>
  </div>
</div>

Answer №1

The instruction read informs Angular about what to read. It can be excluded to read the default.

Therefore, in your situation, both should function:

@ViewChild('serverContentInput', { read: ElementRef, static: false })
@ViewChild('serverContentInput', { static: false })

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

Playing noughts and crosses with the minimax strategy

I am struggling with understanding the minimax algorithm and have been working on it for 2 days without success. Can anyone take a look at my code and help me identify any errors? export default class TicTacToeController { /*@ngInject*/ constructor($s ...

Is it possible to use TypeScript in a React Native project with a JavaScript file?

Currently, I am learning React Native by working on app clones like Instagram and YouTube. I have recently started an AirBnb clone project, but I'm facing some issues with the initial build. One issue I noticed is that in 'App.js', the temp ...

Guide on uploading a file to Pinata directly from a React application

I keep encountering the 'MODULE_NOT_FOUND' console error code. Displayed below is the complete console error: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f4b4d564b5a4d4d5e4c1251505b5a7f0e110f110f">[email& ...

The importance of manually loading extensions and utilizing Ajax effectively for renderPartial

Within my yii application, I have implemented Tabs and am loading content via ajax using renderPartial(). To prevent redundant script loading, I have set processOutput to false. As a result, I aim to manually load all necessary scripts once on the index pa ...

Refresh a webpage content dynamically without the need to reload the entire page

How can I implement YouTube's page navigation system that does not require the entire page to reload when switching pages? Do I need to incorporate Javascript or utilize an API for this functionality? ...

ways to instantly showcase the input's value within a DIV element

For example, I have a div with the ID of "someDiv" and an input text field with the ID of "someInput". How can I make it so that the value entered into the input field displays in the DIV in real time? For instance, if I type the letter "a" in the input fi ...

What is the best way to ensure that the state is updated only when the user begins typing in a text

I am currently working on a text editor-related code and my main focus is to update the state of the editor only when the user starts typing in the editor. The state should be updated under the following scenarios: 1. Update the state when the user begin ...

Update annotations in a React.js powered app similar to Google Keep

I am currently working on developing a replication of the Google Keep application using react js. So far, I have successfully implemented all the basic features such as expanding the create area, adding a note, and deleting it. However, I am facing challen ...

Zoomsounds: Injecting fresh content into div using data-source attribute

Currently, I am utilizing a javascript audio player called ZoomSounds. It generates circular play button divs and injects content into them using the following code: <div id="ap3" class="audioplayer-tobe skin-minimal" style="po ...

Tips for managing onClick code when a user selects "open link in new tab" within a React js environment

How can I ensure that my tracking code runs when a user clicks a button in my React project, even if they open it in a new tab? Is there a solution for this in React JS? Here's a simple example: var Hello = React.createClass({ render: function( ...

Error encountered: Element cannot be clicked on at specified coordinates - Angular/Protractor

Recently, I have been testing out CRUD functionality in an Angular app using Protractor. One recurring issue I've encountered is with the create/edit buttons, which all open the same modal regardless of the page you're on. The frustrating part i ...

What is the correct way to integrate a new component into my JHipster + Angular project while ensuring that the routerlink functions properly?

After creating a new application on JHipster, I wanted to add a FAQ page to my web portal. However, the default CRUD components generated by JHipster made it look more like an admin/user view table. I needed to make the FAQ page accessible to visitors with ...

What is the best way to execute a code once another has successfully completed its run?

Within milliseconds, I am required to update a JSON file with new data and then fetch that updated information. However, after posting the data into the JSON file, it appears that when attempting to retrieve it, the old data is returned instead of the newl ...

What is the best way to retrieve a variable within a nested function?

I'm struggling to access a variable from within a nested function in the following code: $(function() { var key = getRandomKey(dictionary); resetInputRow(dictionary[key]); $("#button").click( function() { var answer = key; ...

Attempting to showcase the text within an <a> element on a <canvas> element while ensuring there are no noticeable visual distinctions

Imagine having this snippet of code on a webpage: elit ac <a href="http://www.ducksanddos/bh.php" id='link'>Hello world!</a> nunc Now, picture wanting to replace the <a> tag with a <canvas> element that displays the same ...

Reading and decoding JSON data using AJAX

Upon viewing the console, I receive the JSON data in the following format: [Object] 0: Object address: "soham" region: "soham" relevanceScore: "4" startDate: "2015-05-10" subscriptionType: "1" verificationStatus: "1" __pro ...

The NodeJS program fails to authenticate the Google Calendar API integration, resulting in an undefined response even when valid credentials and tokens are provided

I am seeking assistance with my Google Calendar API integration in NodeJS. I am encountering an error message indicating that the daily limit for unauthenticated use has been exceeded, requiring signup for continued usage. Despite researching this issue on ...

having difficulty sending the username and password from the HTML page to the controller in AngularJS

In my AngularJS controller, I am having trouble retrieving the values of the username and password fields after submitting the login form. Here is the HTML code for the form: <form class="form-signin" action="" method="post"> ...

The Mongoose query for the id field retrieves both the id and _id values

Within my Mongoose schema, there is a specific field named id which holds a unique identifier for each document. This operates using the same system as the standard _id field as shown below: var JobSchema = new mongoose.Schema({ id: { type:String, requi ...

How can I disable a select element in Laravel 5?

Hey everyone! Currently using Laravel 5 and trying to style the "select" class as "selectpicker". I'm facing an issue where I want to disable or hide the selected option when clicked, as I'm creating a div with the option's content right b ...