Nes*_*ano 9 javascript web angular angular8
我正在尝试访问childView实例,但一直在说childView是未定义的。
这是我的childViews代码:
@ViewChild(CreateQuestionnaireComponent,{ read: true, static: false }) private childQuestionnaireDialog:CreateQuestionnaireComponent;
@ViewChild(ProjectNavbarComponent,{ read: true, static: false }) private childProjectNavBar:ProjectNavbarComponent;
@ViewChild(QuestionnaireNodeComponent,{ read: true, static: false }) private childQuestionnaireNode:QuestionnaireNodeComponent;
....
onCreateTerminal() {
this.childQuestionnaireDialog.generateQuestionnaireDropDownList();
this.childQuestionnaireDialog.resetFields();
this._hideQuestionnaireDialog = false;
this._modalTitle = 'New Terminal';
this._placeHolderText = 'Terminal Questionnaire Title';
this._terminal = true;
}
Run Code Online (Sandbox Code Playgroud)
...
它说:“ this.childQuestionnaireDialog未定义”。
它正在使用Angular 7。
根据我的新知识,@viewChild带有一个称为static的标志。如果将标记设置为true,则父组件将尝试在其自身创建期间获取对childView的引用。换句话说,我们可以在父Component的onInit()方法中拥有childView的实例,基本上是一次访问,因为我们无法使用任何其他方法进行访问。
设置为false的标志基本上是常春藤渲染器中的新方法。
就我而言,这是一个问题,两个选项都不起作用。
Man*_*Mel 18
我有一个类似的问题,其中 ViewChild 组件在 onInit() 方法中未定义。
// Ensure Change Detection runs before accessing the instance
@ContentChild('foo', { static: false }) foo!: ElementRef;
// If you need to access it in ngOnInit hook
@ViewChild(TemplateRef, { static: true }) foo!: TemplateRef;
Run Code Online (Sandbox Code Playgroud)
Har*_*tel 14
您必须在视图完成初始化之前尝试访问 ViewChild 查询的结果。
因此,您可以将查询标记为静态:
@ViewChild('test', {static: true}) test: ElementRef;
Run Code Online (Sandbox Code Playgroud)
...或将逻辑移至 ngAfterViewInit (首选)。
参考https://angular.io/guide/static-query-migration
就我而言,我让我的孩子处于 *ngIf 条件。因此 ViewChild 无法初始化所需的元素。已更新逻辑以在 *ngIf 外部渲染组件,从而通过 ViewChild 能够成功初始化元素。
因此,如果可能的话,当需要 ViewChild 时,更改逻辑以在 *ngIf 外部渲染组件并显示适当的消息。或者使用 CSS 隐藏元素的可见性,而不是 *ngIf。
我花了一个小时没有找到它,所以它也可能对其他人有帮助:我的错误是我在角度html中使用了错误的选择器。我想引用的组件如下所示:
@Component({
selector: 'app-universal-modal',
templateUrl: './universal-modal.component.html',
styleUrls: ['./universal-modal.component.scss']
})
export class UniversalModalComponent implements OnInit {
Run Code Online (Sandbox Code Playgroud)
现在我在其父级中使用了 viewchild :
@ViewChild('universalModalComponent', {static: true}) universalModalComponent: UniversalModalComponent;
Run Code Online (Sandbox Code Playgroud)
html 选择器应该是app-universal-modal:
<app-universal-modal #universalModalComponent ></app-universal-modal>
Run Code Online (Sandbox Code Playgroud)
但我使用了新任务选择器。
奇怪的是,没有编译时错误,但运行时错误......
根据文档,读取的元数据属性是:
`read - read a different token from the queried elements.`
Run Code Online (Sandbox Code Playgroud)
换句话说,如果您想读入ViewContainerRef组件名称而不是普通名称ElementRef(如果您省略,则这是默认名称read),则使用它。因此,将true值设置为true从元素返回类型,据我所知这是不可能的。
这里有一个更好的解释,但对您问题的简短回答是取出属性read或指定ElementRef您想要的特定类型。
| 归档时间: |
|
| 查看次数: |
4146 次 |
| 最近记录: |