Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 247
Parvesh kumar Avatar asked Feb 14 '26 12:02

Parvesh kumar


2 Answers

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'));
}
like image 148
Alexandre Annic Avatar answered Feb 17 '26 01:02

Alexandre Annic


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

like image 28
axl-code Avatar answered Feb 17 '26 02:02

axl-code