In my angular2 project, I created a form with the following code:
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));
}
}
When accessing the nativeElement in ngAfterViewInit, I encountered an issue with undefined values unless I removed the "ngForm" part from #foobar = "ngForm". To resolve this, I made the following adjustments:
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));
}
}
To enhance the solution, I added an auxiliary hashtag (#tralala) to the input element, not related to ngForm. This workaround resolved the issue, but I find it to be a bit hacky. I am still exploring more elegant and straightforward ways to access the native element of the textbox using @ViewChild or this.form.controls without resorting to such workarounds.
Additional note: I am using Angular2 2.0-beta7 for this implementation.