【发布时间】:2017-02-05 08:02:05
【问题描述】:
我在应用模板(根组件的模板)中定义了一个微调器/加载器元素,例如
<!--I have it here so that I don't have to paste it in all my templates-->
<div #spinner></div>
在我的子组件中,我尝试使用@ViewChild 访问它,但这似乎总是返回未定义。我在子组件中访问它的代码是
@ViewChild('spinner', { read: ViewContainerRef }) container: ViewContainerRef; //this is always undefined
但是,当我将 #spinner 放在子组件的 HTML 中时,它会被正确拾取。
有没有办法将子组件中父组件中定义的元素作为ContainerRef?
我需要视图引用以使用ComponentFactoryResolver 在其上动态创建组件。
这似乎是一个similar 问题,但找不到解决方法。
编辑:我现在正在使用可观察的共享服务,但它仍然没有在 .next 上引发事件。
这是我在SpinnerComponent中的代码
@Component({
selector: 'spinner',
styleUrls: ['app/styles/spinner.component.css'],
template:
`<div [hidden]="state.visible" class="in modal-backdrop spinner-overlay"></div>
<div class="spinner-message-container" aria-live="assertive" aria-atomic="true">
<div class="spinner-message" [ngClass]="spinnerMessageClass">{{ state.message }}</div>
</div>`
})
export class SpinnerComponent {
constructor(spinnerService: SpinnerService) {
spinnerService.spinnerStatus.subscribe(event => {
console.log('Event: ' + event); <= not getting called
this.state.visible = event;
});
}
public state = {
message: 'Please wait...',
visible: false
};
}
在 SpinnerService 中,我有
@Injectable()
export class SpinnerService {
public events: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public get spinnerStatus(): Observable<boolean> {
return this.events.asObservable();
}
public showSpinner() {
this.events.next(true);
}
public hideSpinner() {
this.events.next(false);
}
}
在调用组件中,我有
@Component({
selector: 'edit-auction',
templateUrl: '/auctions/edit.html'
})
export class EditAuctionComponent {
constructor(public spinnerService: SpinnerService) { }
ngAfterViewInit() {
//start the spinner
this.spinnerService.showSpinner();
}
}
在 app.module.ts(根模块)中
@NgModule({
imports: [BrowserModule, FormsModule, HttpModule, routes],
declarations: [..],
providers: [NotificationsService, SpinnerService],
bootstrap: [AppComponent]
})
export class AppModule { }
【问题讨论】:
-
顾名思义,
@ViewChild只能用于选择孩子。你想用这个来达到什么目的?如果要显示/隐藏微调器,为什么不使用自定义微调器组件,在其中注入服务发射事件来显示/隐藏微调器。看看这个例子:stackoverflow.com/a/42041945/1153681 -
是否调用了 ngAfterViewInit?
-
是的,我在
showSpinner之前添加了一个警报,它被调用了 -
是否调用了 SpinnerComponent.constructor?
-
不,这不会被调用!当我把它放在应用程序组件中时,它似乎可以工作!