【发布时间】:2018-06-05 02:44:35
【问题描述】:
我的问题是关于 Angular 2/4/5 模块。
在模块中使用 @ViewChild 时无法正常工作,子级未定义。在我将它用作简单组件之前,它运行良好。 *尝试过@ViewChildren 也...相同
代码示例 -
app.module.ts -
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MyNewModule} from './modules/MyNewModule/MyNewModule.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
MyNewModule,
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule { }
app.component.ts -
import { Component, OnInit } from '@angular/core';
import { MyNewModule} from './modules/MyNewModule/MyNewModule.module';
@Component({
selector: 'app-root',
template: `<button (click)="Print()">Print child</button>
<my-new-module></my-new-module>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private MyModule:MyNewModule){}
ngOnInit(){}
Print(){
this.MyModule.Print();
}
}
modules/MyNewModule/MyNewModule.module -
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyNewModule} from './MyNewModule.component';
@NgModule({
imports: [
CommonModule,
],
declarations: [MyNewModule],
providers: [MyNewModule],
exports: [MyNewModule],
})
export class MyNewModule{ }
modules/MyNewModule/MyNewModule.ts-
import { Component, OnInit, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
@Component({
selector: 'my-new-module',
template:`<ng-template #Container></ng-template>`
})
export class MyNewModule implements OnInit {
@ViewChild('Container', {read: ViewContainerRef}) private container: ViewContainerRef;
constructor(){}
ngOnInit(){}
Print(){
console.log(this.container); => undefined
}
}
当尝试在线搜索答案时,我发现的唯一解决方案是尝试@ViewChildren,或者它可能会发生,因为视图尚未初始化。所以我什至尝试在 5 秒的超时时间内完成它......结果相同。 再次使用相同的代码,但作为一个简单的应用程序而不是模块工作正常。
感谢阅读! :)
【问题讨论】:
-
你在哪里打电话
Print()? -
为什么你的组件命名为
MyNewModule而不是MyNewComponent?我认为这给您带来了一些问题。此外,您不能将组件放入providers数组中。 -
@Und3rTow 已修复,已添加到 app.component.ts 模板中:)
-
@BunyaminCoskuner 我不是,它只是为了这个演示。将其从提供程序数组中删除会给我一个错误 - StaticInjectorError
-
你为什么还要尝试将 Angular 模块注入到组件中?
标签: javascript angular dom module viewchild