【发布时间】:2016-10-29 20:15:52
【问题描述】:
我正在尝试设置一个 Angular2 组件,该组件自动聚焦通过内容投影插入的输入元素。
我使用的解决方案基于this answer。我还有一个额外的要求,即输入元素可能嵌套在另一个组件中。但是,我发现ContentChild 查询无法检测到深埋在ng-content 标签内的元素。
@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;
}
}
_autoFocus 属性永远不会被填充。相比之下,auto-focus 指令没有嵌套在另一个组件中并且工作正常。有没有办法让这个工作?
(我没有粘贴AutoFocus 的代码,因为它对这个示例并不重要。)
请参阅Plunker 以获取演示。
更新上面的代码来修复缺失的指令。
【问题讨论】:
-
似乎不支持。
ViewQuery(已弃用)支持descendants: true,但其他类似(未弃用的功能似乎不支持。 -
这很不幸。这个问题有不同的解决方案吗?本质上,我需要一个通用的模态组件,其主体可以是另一个共享组件(例如用于添加和编辑项目的通用表单),并且我想在显示模态时自动聚焦第一个元素。
-
我猜github.com/angular/angular/issues/8563 会让这更容易。除此之外我没有任何想法。
标签: typescript angular