Venkateswaran
Venkateswaran

Reputation: 19

Fetching Property in Angular 7

I want to use the property of the input element when form is submitted. I read the concept of Template reference variable which helps in achieving this case in Angular.

When i assign 'id' attribute of input element with a value and later when i tried fetching, it throws an error. It allows only template reference variable to extract the property.

Why not we access the property of the input element by directly invoking its ID attribute

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-test',
  // templateUrl: './test.component.html',
  template : `
  <input type="text" id = "{{idOne}}"  #idTwo/>
  <button type="text" (click) = 
handleClickEvent(id.value)>Submit</button>

<button type="text" (click) = handleClickEvent(idTwo.value)>Submit 
Again</button>`,
  styles: [`p {color : red}`]
})
export class TestComponent implements OnInit {

  handleClickEvent = (value : string) =>{
    console.log(value);
  }

  public idOne = "testID";
  constructor() { }

  ngOnInit() {
  }

}

When i submit 1st button (which invokes ID directly), it throws error saying

cannot read value of undefined.

When i submit 2nd button, it prints correct value that i inputted.

So my question is

Is template reference variable the only way to fetch the property of the HTML element ?

Can you not fetch the property in a traditional way (directly calling id property) ?

Upvotes: 0

Views: 211

Answers (1)

theMayer
theMayer

Reputation: 16157

Using JavaScript on DOM elements directly is not generally something that is necessary in Angular.

You need to adjust your code as follows:

  • In the component class, declare your properties for binding on the template
  • Create a click handler for the button

Component

export class TestComponent {

  idVal = 'testID';  

  submit(): void {
    // Not sure what needs to happen here.
  }    

  submitAgain(): void {
    // Not sure what needs to happen here.
  }    

  constructor() { }
}

Then, in your template, bind the input field to the the property, and the click handler to the button.

Template

<input type="text" [(ngModel)]="idVal" />

<button type="text" (click)="submit()">Submit</button>    
<button type="text" (click)="submitAgain()">Submit Again</button>

Rules

  • Don't use DOM to store/retrieve values from form fields. That is what ngModel is for.
  • Don't pass arguments in to event handler methods. The data needed for event handlers should be contained as property values on the component.

Upvotes: 1

Related Questions