Parvesh kumar
Parvesh kumar

Reputation: 295

How to get the attribute value from FormControl object in angular2?

I have limited knowledge in angular2. By using the jquery, we can easily get the attribute value. e.g In HTML

 <input id="foo" type="text" name="foo">

In jquery

$(document).ready(
    function ()
    {
           console.log($('#foo').attr('type'));// output foo
    });

In angular2, if we use the reactive form, we write input field like this:

<input formControlName="name" id="foo" type="text" name="foo">

My requirement is getting the value of an attribute(name) dynamically in Component.

Upvotes: 3

Views: 15009

Answers (3)

Suren Srapyan
Suren Srapyan

Reputation: 68635

One approach you can inject document via DOCUMENT token and use it

constructor(@Inject(DOCUMENT) document) {
    document.getElementById('foo').getAttribute(...)
}

Or use template reference variables like

<input #foo formControlName="name" id="foo" type="text" name="foo">

and in the component use

@ViewChild('foo') foo: ElementRef;

ngAfterViewInit() {
   console.log(this.foo.nativeElement);
}

The original element will be accessible via nativeElement property.

Upvotes: 1

axl-code
axl-code

Reputation: 2274

If you are using the reactive way I recommend you this setup:

In your component:

import { FormControl } from '@angular/forms';

export class YourComponent {
  myForm: FormGroup;

  constructor() {
    this.myForm = new FormGroup ({
      name: new FormControl()
    });
  }

  onSubmit(): void {
    console.log(this.myForm.value.name);
  }
}

Your html:

<form [formGroup]="myForm" novalidate>
  <div class="form-group">
    <label class="center-block">Name:
      <input class="form-control" formControlName="name">
    </label>
  ...

For more information: Angular docs

Upvotes: 1

Alexandre Annic
Alexandre Annic

Reputation: 10738

You can do something like that

Template:

<input #myinput formControlName="name" id="foo" type="text" name="foo">

Class:

@ViewChild('myinput ') input: ElementRef;

ngAfterViewInit() {
   console.log(this.input.nativeElement.getAttribute('type'));
}

Upvotes: 1

Related Questions