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.
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'));
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With