加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何使用Angular 2.0中的formControl访问Native HTML Input元素

发布时间:2020-12-17 06:57:04 所属栏目:安全 来源:网络整理
导读:我正在使用Angular 2.0最终版本. 我想做的事? – 我想只在输入接收焦点时显示一些通知(警告,输入要求).甚至更好,当他的父母(div)有鼠标悬停事件. 从父(div)这样做很容易. Just(focus)= showNotifications()和ngIf – 工作完成了. 但我想在show-notification
我正在使用Angular 2.0最终版本.

我想做的事?
– 我想只在输入接收焦点时显示一些通知(警告,输入要求).甚至更好,当他的父母(div)有鼠标悬停事件.

从父(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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读