【发布时间】:2017-02-08 05:50:24
【问题描述】:
我正在使用 Angular 2.0 最终版本。
我想做什么?
- 我只想在输入接收焦点时显示一些通知(警告,输入要求)。或者更好的是,当他的父母 (the div) 有 mouse hover 事件时。
从父级(div)执行此操作很容易。只需 (focus)=showNotifications() + 一个 ngIf - 就完成了。
但我想将此功能封装在 show-notifications 组件中 - 并使其可重用..
鉴于我使用@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..])
}
show-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>
show-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) 对象,我如何访问本机元素?
有没有更好的方法在单独的组件中进行通知 - 并使其可重用?我已经在整个应用程序中成功地使用了它 - 显示错误和输入要求..
注意:我尝试首先使用主题标签语法 (#myInput) 传递漏洞 html 输入,并在 show-notifications 组件中在那里形成,我尝试这样做:myInput.myName - 访问控件但我未定义。本机输入元素上不存在这些控件。我需要该控件进行验证:)
【问题讨论】:
-
一种选择是创建自定义表单控件。您可以让用户使用#input 传入 HTML,以便将其绑定到要使用的
ControlValueAccessor字段。
标签: angular rxjs angular2-forms onfocus angular2-formbuilder