首页 > 解决方案 > 角度关注表单控制

问题描述

我有以下输入:

 <input
                #participantInput="ngModel"
                id="participantInput"                  
                pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"
                class="cell small-7"
                placeholder="John.Doe@gmail.com"
                [(ngModel)]="newParticipantMail"
                (keyup.enter)="addParticipant()"
                style="height:10%;">

因为#participantInput="ngModel"

我无法像这样检索 elementRef:

@ViewChild('participantInput') participantInput: ElementRef;

那么,我怎样才能将重点放在那个领域呢?

标签: formsfocusangular6

解决方案


您可以像这样添加另一个模板变量:

 <input
            #participantInput="ngModel"
            #participantRef
            id="participantInput"                  
            pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"
            class="cell small-7"
            placeholder="John.Doe@gmail.com"
            [(ngModel)]="newParticipantMail"
            (keyup.enter)="addParticipant()"
            style="height:10%;">

然后您可以将其访问到您的组件中

@ViewChild('participantRef') participantRef: ElementRef;

显然你必须等待视图初始化,例如实现AfterViewInit接口


推荐阅读