我正在尝试设置一个 Angular2 组件,该组件自动聚焦通过内容投影插入的输入元素。
我使用的解决方案基于这个答案 https://stackoverflow.com/a/34503163/1592971。我还有一个额外要求,即输入元素可以嵌套在另一个组件内。然而,我发现ContentChild
查询无法检测深埋在内部的元素ng-content
tags.
@Component({
selector: 'inner-feature',
template: "<input auto-focus>",
directives: [AutoFocus]
})
export class InnerFeature { }
@Component({
selector: 'feature',
template: `
<div [class.hide]="!show">
<ng-content></ng-content>
</div>
`
})
export class Feature {
@ContentChild(AutoFocus)
private _autoFocus: AutoFocus;
private _show: boolean = false;
@Input()
get show() {
return this._show;
}
set show(show: boolean) {
this._show = show;
if (show && this._autoFocus) {
setTimeout(() => this._autoFocus.focus());
}
}
}
@Component({
selector: 'my-app',
template: `
<div>
<button (click)="toggleFeature()">Toggle</button>
<feature [show]="showFeature">
<inner-feature></inner-feature>
</feature>
</div>
`,
directives: [Feature, InnerFeature]
})
export class App {
showFeature: boolean = false;
toggleFeature() {
this.showFeature = !this.showFeature;
}
}
The _autoFocus
财产永远不会被填充。与以下情况进行对比auto-focus
指令没有嵌套在另一个组件中,并且工作正常。有办法让这项工作发挥作用吗?
(我还没有粘贴代码AutoFocus
因为这对于这个例子来说并不重要。)
See Plunker http://plnkr.co/edit/t8DVXjfrhbBZylSF90DJ?p=preview进行演示。
UPDATED上面的代码修复了缺失的指令。
Use ContentChildren
with descendants
set to true
@ContentChildren(AutoFocus, { descendants: true })
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)