When attempting to access the .nativeElement of an input using @ViewChild, the result is 'undefined' rather than the expected value

In my angular2 project, I created a form with the following code:

import {Component, ElementRef, ViewChild, AfterViewInit} from "angular2/core";
import {Observable} from "rxjs/Rx";
import {ControlGroup, Control, Validators, FormBuilder} from "angular2/common";

@Component({
    selector: "ping-pong",
    template: `
                  <form
                     name="someform"                             [ngFormModel]="form">
                      <div class="form-group">
                          <input                                 
                              id="foobar"                        #foobar="ngForm"   <-- without ="ngForm" everything works fine
                              type="text"                        ngControl="foobar"
                              value=""
                              class="form-control"
                          />
                      </div>
                  </form>
              `,
    styles: [`
                  form {
                      width: 300px;
                  }
              `]
})

export class ChangepswdFormComponent implements AfterViewInit {
    @ViewChild("foobar") foobar: ElementRef;
    private form: ControlGroup;

    public constructor(formBuilder: FormBuilder) {
        this.form = formBuilder.group({
            foobar: [""]
        });
    }

    public ngAfterViewInit(): void {
        console.log(this.foobar.nativeElement);
        //observable doesnt work because nativeelement is undefined
        //Observable.fromEvent(this.foobar.nativeElement, "keyup").subscribe(data => console.log(data));
    }
}

When accessing the nativeElement in ngAfterViewInit, I encountered an issue with undefined values unless I removed the "ngForm" part from #foobar = "ngForm". To resolve this, I made the following adjustments:

import {Component, ElementRef, ViewChild, AfterViewInit} from "angular2/core";
import {Observable} from "rxjs/Rx";
import {ControlGroup, Control, Validators, FormBuilder} from "angular2/common";

@Component({
    selector: "ping-pong",
    template: `
                  <form
                     name="someform"                             [ngFormModel]="form">
                      <div class="form-group">
                          <input                                 
                              id="foobar"                        #foobar="ngForm"     #tralala
                              type="text"                        ngControl="foobar"
                              value=""
                              class="form-control"
                          />
                      </div>
                  </form>
              `,
    styles: [`
                  form {
                      width: 300px;
                  }
              `]
})

export class ChangepswdFormComponent implements AfterViewInit {
    @ViewChild("tralala") foobar: ElementRef;
    private form: ControlGroup;

    public constructor(formBuilder: FormBuilder) {
        this.form = formBuilder.group({
            foobar: [""]
        });
    }

    public ngAfterViewInit(): void {
        console.log(this.foobar.nativeElement);
        let keyups = Observable.fromEvent(this.foobar.nativeElement, "keyup");
        keyups.subscribe(data => console.log(data));
    }
}

To enhance the solution, I added an auxiliary hashtag (#tralala) to the input element, not related to ngForm. This workaround resolved the issue, but I find it to be a bit hacky. I am still exploring more elegant and straightforward ways to access the native element of the textbox using @ViewChild or this.form.controls without resorting to such workarounds.

Additional note: I am using Angular2 2.0-beta7 for this implementation.

Answer №1

To solve the issue, simply introduce another template variable

#foo="ngForm" #fooElement
@ViewChild("fooElement") foo: ElementRef;

By changing the value to "ngForm", the template variable will serve a different function and will not be compatible with @ViewChild()

If you believe this functionality should still be supported, please consider filing a bug report.

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

Encountering a 'blocked:other' error status while making a REST API call in my Angular application to retrieve data from the server

Example of the requested REST API URL: http://example.com/controller/api?bannerId=1&value=23 Encountering a browser error status: blocked:other while attempting to make an HTTP request to the server from the Angular application. ...

Animation of lava effect in Angular 7

I have a unique Angular 7 application featuring a homepage with a prominent colored block at the top, along with a header and various images. My goal is to incorporate lava effect animations into the background similar to this CodePen example. If the link ...

Tips on adjusting sticky behavior for responsiveness using bootstrap-4

In my project, I am utilizing angular with bootstrap. The header of the project consists of two parts and a content area. However, when the resolution is small, the header wraps. Check out the header and content on large screens View the header and conte ...

Rounding Decimals using JavaScript

I am facing the challenge described in this particular query. In most cases, my code works fine to round numbers to two decimal places with the following formula: Math.round(num * 100) / 100 However, there was a peculiar scenario where it failed. When tr ...

Using TypeScript to define callback functions within the Cordova.exec method

I'm encountering an issue with the TypeScript definition for Cordova. The codrova.d.ts file doesn't allow for any function arguments in the success-callback and error-callback. To better illustrate my problem, here's a small example: Here ...

Tips for easily navigating Angular google Maps

<agm-map [zoom]="mapConfig.zoom" [styles]="mapConfig.styles" [latitude]="currLate" [longitude]="currLongi" > <agm-direction *ngIf="path" [origin]="path.origin" [destination]="path.destination" ...

Using TypeScript with Nuxt/Vue.js: The 'components' property cannot be specified in an object literal as it is not recognized in the 'VueClass' type

I am puzzled by the error message I am receiving when using a decorator in conjunction with components and middleware: https://i.sstatic.net/dutqx.png When I examine the error, it states: TS2345: Argument of type '{ components: { Test: typeof Nav; } ...

How to store property transformation in Redux/ngrx

I have the following setup someReducer.ts export interface State { someProp: MyModel; } // some action listeners .. // // export const getProp = (state: State) => state.someProp; selector.ts export const getProperty = createSelector(getState, f ...

Manage scss styles consistently across Angular projects with this Angular library designed to

In an effort to streamline my development process, I am looking to consolidate my commonly used styles that are defined in my Angular library. My goal is to easily leverage mixins, functions, variables, and more from my library in future projects. Previou ...

How can I display the value of a variable within an Angular 4 component directly from the console?

In my Angular 4 component, I store a simple key in a variable. However, I am aware that when the app is closed, all values within the variable are erased. Here is an example of this: export class LoginComponent implements OnInit { data : any; const ...

Verifying the Presence of an Image in the Public Directory of Next JS

My TypeScript Next.js project contains a large number of images in the public folder. I am wondering if there is a way to verify the existence of an image before utilizing the <Image /> component from next/image. I have managed to achieve this using ...

Ways to invoke main.ts to communicate with an Angular component using Electron

I have a good understanding of how to communicate between an angular app and the electron main thread using IPC. However, in my current scenario, I have threads running in the electron main thread for video processing. After these threads complete their t ...

Encountered a hitch while trying to start an angular 2 app using npm

Encountering an error while compiling the application with @angular/cli version 1.2.4 @angular/cli: 1.2.4 node: 8.11.1 os: win32 x64 @angular/animations: 4.3.6 @angular/common: 4.3.6 @angular/compiler: 4.3.6 @an ...

Using Angular Form Builder to assign a value depending on the selected option in a dropdown menu

My approach to Angular Form Builder initialization includes a group that looks like this: contactReason: this.formBuilder.group({ description: '', source: this.sourceType() }) For the 'description' field, I hav ...

Tips for modifying HTML template code within a Typescript document using Atom

There appears to be a current trend in Angular development where the template code is embedded within the Angular component, usually found in a Typescript or Javascript file. However, when attempting this approach, I noticed that I am missing html syntax ...

Troubleshooting a unique Flex layout problem in Angular 2 with Angular Material

Can anyone help me figure out how to recreate this design using Flex within my Angular2 materialDesign stack? https://i.stack.imgur.com/le1ld.png Currently, I'm facing an issue where blocks 2 and 3 keep ending up below block 4... https://i.stack.im ...

Navigating the proper utilization of exports and subpaths in package.json with TypeScript

As a newbie in creating npm packages using TypeScript, I've encountered some issues that I believe stem from misinterpreting the documentation. Currently, I am working with Node 16.16.0 and npm 8.13.2. Here is the structure of my project: src/ ├─ ...

Nativescript encountered an issue while attempting to generate the application. The module failed to load: app/main.js

I'm currently experimenting with the sample-Groceries application, and after installing NativeScript and angular 2 on two different machines, I encountered the same error message when trying to execute: tns run android --emulator While IOS operations ...

Encountering a 'ng serve' error while trying to include a new SCSS style in an

I recently created a fresh Angular application using the CLI. For my stylesheet, I opted for SCSS. Upon running the application with ng serve, everything was running smoothly. However, when I added some styles to the stylesheet, such as: body { backgr ...

Organize information in a React table following a predetermined sequence, not based on alphabetical order

As a beginner with React, I'm looking to sort my data by the column "Status" in a specific order (B, A, C) and vice versa, not alphabetically. The data structure looks like this: export interface Delivery { id: number; name: string; amount: num ...