我在angular2中创建了以下表单:
import {Component, ElementRef, ViewChild, AfterViewInit} from "angular2/core";
import {Observable} from "rxjs/Rx";
import {ControlGroup, Control, Validators, FormBuilder} from "angular2/common";
@Component({
selector: "ping-pong",
template: `
<form
name="someform" [ngFormModel]="form">
<div class="form-group">
<input
id="foobar" #foobar="ngForm" <-- without ="ngForm" everything works fine
type="text" ngControl="foobar"
value=""
class="form-control"
/>
</div>
</form>
`,
styles: [`
form {
width: 300px;
}
`]
})
export class ChangepswdFormComponent implements AfterViewInit {
@ViewChild("foobar") foobar: ElementRef;
private form: ControlGroup;
public constructor(formBuilder: FormBuilder) {
this.form = formBuilder.group({
foobar: [""]
});
}
public ngAfterViewInit(): void {
console.log(this.foobar.nativeElement);
//observable doesnt work because nativeelement is undefined
//Observable.fromEvent(this.foobar.nativeElement, "keyup").subscribe(data => console.log(data));
}
}
在ngAfterViewInit内部,nativeElement位未定义,除非我删除=&#34; ngForm&#34;部分来自#foobar =&#34; ngForm&#34;。我通过进行以下调整克服了这个问题:
import {Component, ElementRef, ViewChild, AfterViewInit} from "angular2/core";
import {Observable} from "rxjs/Rx";
import {ControlGroup, Control, Validators, FormBuilder} from "angular2/common";
@Component({
selector: "ping-pong",
template: `
<form
name="someform" [ngFormModel]="form">
<div class="form-group">
<input
id="foobar" #foobar="ngForm" #tralala
type="text" ngControl="foobar"
value=""
class="form-control"
/>
</div>
</form>
`,
styles: [`
form {
width: 300px;
}
`]
})
export class ChangepswdFormComponent implements AfterViewInit {
@ViewChild("tralala") foobar: ElementRef;
private form: ControlGroup;
public constructor(formBuilder: FormBuilder) {
this.form = formBuilder.group({
foobar: [""]
});
}
public ngAfterViewInit(): void {
console.log(this.foobar.nativeElement);
let keyups = Observable.fromEvent(this.foobar.nativeElement, "keyup");
keyups.subscribe(data => console.log(data));
}
}
换句话说,我用一个与ngForm无关的辅助主题标签(#tralala)丰富了输入元素。即使这个解决方案有效,我也不会感到安心,因为感觉就像我一样。应用小黑客。我们应该能够以更优雅/直接的方式通过@ViewChild或通过this.form.controls(或类似的东西)检索文本框的本机元素,而不使用像我使用的那样的变通方法。但我无法确切地知道如何。
快速附录:如果有任何重要的话,我会使用Angular2 2.0-beta7。
答案 0 :(得分:28)
只需添加另一个模板变量
#foobar="ngForm" #foobarElement
@ViewChild("foobarElement") foobar: ElementRef;
使用="ngForm"
模板变量有不同的用途,不适用于@ViewChild()
如果您认为这仍然可行,请考虑创建错误报告。