我对angular2的了解有限。通过使用jquery,我们可以轻松获取属性值。 例如 在HTML中
<input id="foo" type="text" name="foo">
在jquery中
$(document).ready(
function ()
{
console.log($('#foo').attr('type'));// output foo
});
在angular2中,如果我们使用反应形式,我们就像这样编写输入字段:
<input formControlName="name" id="foo" type="text" name="foo">
我的要求是在Component中动态获取属性(名称)的值。
答案 0 :(得分:1)
你可以做那样的事情
模板:
<input #myinput formControlName="name" id="foo" type="text" name="foo">
类别:
@ViewChild('myinput ') input: ElementRef;
ngAfterViewInit() {
console.log(this.input.nativeElement.getAttribute('type'));
}
答案 1 :(得分:0)
您可以通过DOCUMENT
令牌注入文档并使用它的一种方法
constructor(@Inject(DOCUMENT) document) {
document.getElementById('foo').getAttribute(...)
}
或使用模板参考变量,如
<input #foo formControlName="name" id="foo" type="text" name="foo">
并在组件中使用
@ViewChild('foo') foo: ElementRef;
ngAfterViewInit() {
console.log(this.foo.nativeElement);
}
可以通过nativeElement
属性访问原始元素。
答案 2 :(得分:0)
如果您使用的是反应方式,我建议您使用此设置:
在您的组件中:
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);
}
}
你的HTML:
<form [formGroup]="myForm" novalidate>
<div class="form-group">
<label class="center-block">Name:
<input class="form-control" formControlName="name">
</label>
...
了解更多信息: Angular docs