当引用可以隐藏/"销毁"的输入时(因为使用了*ngIf并且某些元素被销毁),由angular2语法#(在下面的示例中为#test)创建的局部变量不起作用,即使元素存在于页面中.
代码是:
@Component({
selector: 'my-app',
template: `<h1>My First Angular 2 App</h1>
<button (click)="focusOther(test)">test</button>
<input #test *ngIf="boolValue" >
`
})
export class AppComponent {
private isVisible = false;
focusOther(testElement){
this.isVisible = true;
alert(testElement);
testElement.focus();
}
}
Run Code Online (Sandbox Code Playgroud)
警报显示"未定义",因为没有任何内容传递给该函数.
是否有解决方案使其工作?我的目标是集中一个将要创建的元素.
Mark Rajcok给出的解决方案:使用一个使用elementRef并在元素上调用.focus()的afterViewInit创建一个指令.
有关第1部分的工作版本,请参阅此plunker:http://plnkr.co/edit/JmBBHMo1hXLe4jrbpVdv?p = preview
一旦修复了"创建后焦点"的问题,我需要一种重新聚焦()组件的方法,比如"test.focus()"(其中#test是输入的局部变量名,但不能像我之前演示的那样使用).
Mark Rajcok提供的多种解决方案
我可以在文档或谷歌示例中找到这样的东西.
我在div中有很多输入框,我需要以编程方式选择一个.怎么做 ?
就像是
<div>
<input type="text" name="txt1" />
<input type="text" name="txt2" />
<input type="text" name="txt3" />
<input type="text" name="txt4" />
<input type="text" name="txt5" />
<input type="text" name="txt6" />
</div>
<button (click)="selectSample()" />
selectSample() {
?????????('txt3').focus();
console.log('Button pressed, txt3 has been selected');
}
Run Code Online (Sandbox Code Playgroud) 我正在阅读单元测试时遇到一些困难,这个单元测试正在读取一些用*ngIf从DOM中添加/删除的html.
这是DOM:
<div class="detailacc" (click)="showDet()">
<i class="fa" [class.fa-caret-right]="!showHideDet " [class.fa-caret-down]="showHideDet " aria-hidden="true"></i>
<h4>Expandable</h4>
</div>
<div *ngIf="showHideDet">
<p class="detailHeader">Details header</p>
</div>
Run Code Online (Sandbox Code Playgroud)
这是在第一个div的click事件中调用的组件函数:
private showDet() {
console.log('show called');
this.showHideDet = !this.showHideDet;
}
Run Code Online (Sandbox Code Playgroud)
最后这是规范:
it('should show the header when the expandable elem is clicked', async(() =>
{
const fixture = TestBed.createComponent(DetailsComponent);
const compiled = fixture.debugElement.nativeElement;
let detPresent: boolean = false;
for (let node of compiled.querySelectorAll('.detailacc')) {
node.click();
}
setTimeout(() => {
console.log(compiled.querySelectorAll('.detailHeader'));
for (let node of compiled.querySelectorAll('.detailHeader')) {
if (node.textContent === 'Details header') …Run Code Online (Sandbox Code Playgroud) 正如你可以看到我正在使用setTimeout,如果我打算集中我的输入.如果我删除setTimeout焦点不起作用.
<div [hidden]="searchInputHidden">
<input (blur)="hideInput()" #term (keyup)="search(term.value)" type="text" class="inp_top" name="product_name" id="product_name" />
</div>
private showSearchInput(term) {
this.searchInputHidden = false;
setTimeout(function(){
term.focus();
}, 100);
}
Run Code Online (Sandbox Code Playgroud) 我有一个输入字段,当modalOpen = true时添加类激活,这很好.
但是,当这个模态显示时,我希望它专注于输入字段?
<div [class.active]="modalOpen">
<input>
</div>
Run Code Online (Sandbox Code Playgroud)