我在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位是未定义的,除非我从#foobar =“ngForm”中删除=“ngForm”部分.我通过进行以下调整克服了这个问题:
import {Component,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.