我正在使用Angular 2.0 final release。如何使用Angular 2.0中的formControl访问Native HTML Input元素
我想干什么? - 我只想在输入接收焦点时显示一些通知(警告,输入要求)。甚至更好,当他的父母(the div
)有mouse hover
事件。
从父母(div)这样做很容易。 Just(focus)= showNotifications()+ ngIf - 并完成作业。
但我想封装节目的通知组件内部此功能 - 并使其可重复使用..
由于我使用@Input()
通过the control
展会的通知里面 - 我可以,如果两者都做这个事情我可以访问native HTML input element
。你可以在show-notifications.component.ts
看到。下面是代码:
app.component.html:
`<div>
<label>Name: </label>
<input formControlName="myName">
<show-notifications [the_control]="myName" ></show-notifications>
</div>`
app.component.ts:
export class AppComponent {
myName = new FormControl("defaultvalue",[some validators..])
}
显示,notifications.component.html:
<div class="show_requirements" *ngIf="hasfocus or parentDivHasMouseHover"> // incorect code and logic - i know, but you can see the idea..
<p *ngFor="let requirement of thisInputRequirements">{{requirement}}<p>
</div>
显示,notifications.component.ts:
export class ShowNotificationsComponent {
@Input() the_control;
this.thisInputRequirements = // take them form firebase.
this.thisInputCustomErrorMessages = // take them from firebase.
// I implemented all this and works amazing but i want to do:
//something like this:
ngOnInit(){
this.nativeInputElement = this.the_control.getNativeElement() // this of course doesn't work
// the requirements are shown only when the input receive focus
let source = Rx.DOM.focus(this.nativeInputElement);
source.subscribe(x => this.hasFocus = true)
// Or even better:
// the requirements are shown only when the parent has mouse hover
// or any other event/endles posibilites here..
let parent = getParentOf(this.nativeInputElement)
let source = Rx.DOM.mouseover(parent);
source.subscribe(x => this.parentDivHasMouseHover = true) // this will be some toggling functionality.
}
}
问:
我如何访问本地元素因为我有formControl(MYNAME = the_control)对象?
是否有更好的方式在单独的组件中完成通知 - 并使其可重用?我已经在整个应用程序中成功地使用了它 - 显示错误和输入要求。
注意:我试图首先使用hashtag语法(#myInput)传递hole html输入,然后在show-notifications组件,我试图做:myInput.myName - 访问控制,但我得到未定义。本地输入元素上不存在控件。我需要验证:)
一种选择是创建一个自定义表单控件。您可以让用户通过#input传递HTML,以便将其绑定到要使用的“ControlValueAccessor”字段。 –