【发布时间】:2018-04-02 19:49:38
【问题描述】:
我正在使用Angular 5.2.1 开发一个角度网站。我在一个视图中创建了一个我多次使用的组件。要访问它,请在该组件的构造函数中为该组件创建一个唯一的 Id。
在AfterViewInit 事件中,我想订阅一个事件。但似乎在AfterViewInit 被触发后不久该组件仍然不可用。
HTML
<a data-toggle="collapse" href="#{{componentId}}">Toggle</a>
<div id="{{componentId}}" class="collapse">
<!-- tabset content -->
</div>
组件
declare var $: any
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html'
})
export class MyComponentComponent implements OnInit, AfterViewInit {
// Some inputs
public componentId: string
// Some other component variables
constructor(
private generatorService: GeneratorService
) {
// Generate unique Id for the component, length 10
this.componentId = this.generatorService.generateId(10)
}
ngOnInit() {
}
ngAfterViewInit(): void {
console.log(this.componentId) // Correct id is printed to console
console.log($('#' + this.componentId)) // Returning empty result
// So this is not working:
$('#' + this.componentId).on('hide.bs.collapse', () => {
// Do something
})
}
// Some other code
}
据我所知,AfterViewInit 通常在组件完全初始化并添加到 DOM 时触发。当我稍等片刻并手动将$('#[myComponentId]') 写入控制台时,我得到了正确的结果。
我做错了什么?
【问题讨论】:
标签: jquery angular angular-ui-bootstrap angular5