【问题标题】:Angular focus on formcontrol角度关注表单控制
【发布时间】:2018-08-24 09:08:23
【问题描述】:

我有以下输入:

 <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;

那么,我该如何设置该领域的焦点?

【问题讨论】:

  • 我认为你不应该设置#participantInput="ngModel",只设置#participantInput
  • @firegloves 是的,但后来我无法再使用参与者输入.invalid 验证输入

标签: forms focus angular6


【解决方案1】:

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

 <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接口

【讨论】:

  • 非常感谢,解决方案似乎很简单...我不知道您可以在同一个 html 标签上定义多个变量。
  • 是的,这有点令人困惑,但仔细思考它们只是变量,我们将它们绑定到不同的东西
猜你喜欢
  • 1970-01-01
  • 2015-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多