@ViewChild升级到Angular 9后无法正常工作

时间:2020-02-14 16:46:42

标签: angular

升级到Angular 9之后,基本上我所有的@ViewChild引用都不再初始化。

无论如何,

<app-menu-editor #menuEditor>
</app-menu-editor>

<div #cardBody>
  <!-- ... -->
</div>
@ViewChild('menuEditor', {read: MenuEditorComponent}) menuEditor: MenuEditorComponent;

@ViewChild('cardBody', {read: ElementRef}) cardBody: ElementRef;

我不断收到异常消息,例如menuEditorundefined

您知道为什么它不再起作用了吗?

4 个答案:

答案 0 :(得分:11)

尝试

CommandLineRunner

就像PierreDuc所说的那样,也许您是在@ViewChild('menuEditor', {static: true, read: MenuEditorComponent}) menuEditor: MenuEditorComponent; @ViewChild('cardBody', {static: true, read: ElementRef}) cardBody: ElementRef; 中引用它们。

答案 1 :(得分:5)

我猜想您是在undefined钩子内还是在类构造函数内得到了ngOnInit。如果我的猜测是正确的,那么这就是您的问题:

如果您使用@ViewChild装饰器中的ngOnInit选项,则static: true中的视图子项将变为可用。如果未设置static: true选项,则您的视图子项仅在ngAfterViewInit中可用。 static选项设置为false by default

This SO answer可能也有帮助。

答案 2 :(得分:5)

我还有另一种角度为9的情况,我花了两天时间才弄清楚。

我的问题是,没有一种解决方案有效;实际上,ViewChild和ViewChildren都不在ANGULAR 9中工作。

经过大量调查并且没有任何警告,问题是我的The name is: XYZ The mutated name is: XYZ 属于抽象类,没有被标记为@ViewChild

因此,如果您正在做这样的事情:

@Component

这是行不通的。 您还必须在抽象类上添加export abstract class AbstractBaseComponent { @ViewChild('test') public testRef: TestComponent; } @Component({ 'selector': 'base-component' }) export class BaseComponent extends AbstractBaseComponent { ngAfterViewInit() { console.log(this.testRef); } }

@Component

对此的进一步了解可以(间接)在角度9的重大变化中找到:

尽管没有提到抽象类遵循相同的行为,但实际上是按原样进行的,因为抽象类在技术上是不会转译的。

答案 3 :(得分:0)

对于 Angular 8 及更高版本,您可以执行以下操作:

 @ViewChild('txtName', {static: false}) txtName: ElementRef;
    
    { static: true } needs to be set when you want to access the ViewChild in ngOnInit.
        
    { static: false } can only be accessed in ngAfterViewInit. This is also what you want to go for when you have a structural directive (i.e. *ngIf) on your element in your template.