相关疑难解决方法(0)

专注于新添加的输入元素

我有一个新的Angular 2应用程序,其中包含一个输入框列表.当用户点击返回键时,我会在他们当前正在编辑的输入框之后立即添加一个新输入框.或者更确切地说,我(异步)在模型中向数组添加一个新条目,这使得Angular 2在不久的将来自动生成一个新的输入框.

如何使输入焦点自动更改为新添加的元素?

[edit]或者,我得到了一个引起DOM生成的模型对象的引用.从组件代码中,有没有办法搜索表示特定模型对象的DOM元素?

[编辑]这是我的代码,使这项工作.希望这对一些Angular 2开发者来说足够冒犯以鼓励回复:-)

app.WordComponent = ng.core
    .Component({
        selector: 'word-editor',
        template:'<input type="text" [value]="word.word" (input)="word.update($event.target.value)" (keydown)="keydown($event)"/>',
        styles:[
            ''
        ],
        properties:[
            'list:list',
            'word:word'
        ]
    })
    .Class({
        constructor:[
            function() {
            }
        ],
        keydown:function(e) {
            if(e.which == 13) {
                var ul = e.target.parentNode.parentNode.parentNode;
                var childCount = ul.childNodes.length;

                this.list.addWord("").then(function(word) {
                    var interval = setInterval(function() {
                        if(childCount < ul.childNodes.length) {
                            ul.lastChild.querySelector('input').focus();
                            clearInterval(interval);
                        }
                    }, 1);
                });
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

angular

76
推荐指数
4
解决办法
9万
查看次数

如何专注于Angular中的输入

这应该很简单,但是我找不到解决方案,我可以在SO上找到最接近的答案是:我如何以编程方式将焦点设置为Angular2中动态创建的FormControl

但是,这比我的要求更加复杂。我的很简单。我在模板中输入如下:

<div *ngIf="someValue">    
    <input class="form-control" #swiper formControlName="swipe" placeholder="Swipe">
</div>
Run Code Online (Sandbox Code Playgroud)

(请注意,它在ngx-boostrap表单控制组中,但是我敢肯定这应该没关系)

我有一个按钮,当单击该按钮时会调用以下函数:

onClick() {
    this.renderer.invokeElementMethod(this.swiper.nativeElement, 'focus')
}
Run Code Online (Sandbox Code Playgroud)

目的是当单击按钮时,我的输入元素将获得焦点。这是我的其余部分(相关部分):

import { Component, ElementRef, ViewChildren, Renderer } from '@angular/core';
import { MyService } from wherever/my/service/is

export class MyClass {
    @ViewChildren('swiper') input: ElementRef;
    someValue: any = false;

    constructor(private renderer: Renderer, service: MyService) {
       this.service.getSomeData().subscribe(data => {
          this.someValue = true;
       }
    }

    onClick() {
        this.renderer.invokeElementMethod(this.swiper.nativeElement, 'focus');
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

ERROR TypeError: Cannot read property 'focus' of undefined
at RendererAdapter.invokeElementMethod (core.js:12032)
etc...
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

(角度5 …

typescript angular

4
推荐指数
2
解决办法
5138
查看次数

标签 统计

angular ×2

typescript ×1