如何使用Angular 2.0中的formControl访问Native HTML Input元素
我正在使用Angular 2.0最终版本.
我想做的事? 从父(div)这样做很容易. Just(focus)= showNotifications()和ngIf – 工作完成了. 但我想在show-notifications组件中封装此功能 – 并使其可重用.. 鉴于我使用@Input()传递show-notifications中的控件 – 如果我有权访问本机HTML输入元素,我可以做这两件事.你可以在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 – 访问控件但我得到了未定义.控件不存在于本机输入元素上.我需要那个控制来验证:) 解决方法
我认为您可以使用#notation将元素传递给ShowNotificationsComponent:
export class ShowNotificationsComponent { @Input() the_control; @Input() elm; //... } 然后在模板中: <input formControlName="myName" #elm> <show-notifications [the_control]="myName" [elm]="elm"></show-notifications> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |