@ViewChild - Angular 13上的初始化错误

3
我正在创建 Angular 13 应用程序。我想使用 @ViewChild 从 ParentComponent 调用 ChildComponent 的 show() 方法,但是我遇到了错误。旧的问题和答案对于这种情况不起作用。
Parent:
<app-child #child></app-child>

@ViewChild('child') child: ChildComponent;

showChild() {
   this.child.show();
}

子元素:

show(){
  console.log('show');
}

错误:

属性“child”没有初始化程序,且在构造函数中未明确赋值。


解决方案1:

父级组件:

@ViewChild('child') child!: ChildComponent;

错误:

类型错误:无法读取未定义的属性(读取“show”)


解决方案2:

父级:

@ViewChild('child') child: ChildComponent = new ChildComponent;

没有错误 运行良好,但我对其是否正确存有疑虑?

2个回答

4

你可以像这样初始化。它将帮助你解决错误。

@ViewChild('child') child: ChildComponent = {} as ElementRef;

or 

@ViewChild('child') child: ChildComponent = {} as ChildComponent;

1
只需将类型传递给ViewChild也可以工作:https://stackblitz.com/edit/angular-ivy-el9e3r?file=src/app/app.component.ts - enno.void
2
@enno.void链接返回404错误。 - rofrol

2
你的疑问解决方案 -
Parent-
<app-child></app-child>
@ViewChild('child') child: ChildComponent;

ngAfterViewInit() {
    // When accessing with ViewChild(), use this lifecycle hook
    // to call methods or for anything related to that component
    this.child.show();
}

Child-
show(){
  console.log('HELLO WORLD');
}

关于访问子组件的额外信息-

有三种方法可以通过Angular查询子组件、组件的子元素或HTML DOM元素,并且可以获取查询到的DOM或组件对象的最早时刻是在ngAfterViewInit生命周期钩子中。

1.) 基于组件名称查询

app.component.ts

@ViewChild('cardRef', {read: ElementRef}) card1: ElementRef; //by this you can achieve querying over HTML DOM objects
@ViewChild('container') containerDiv: ElementRef;

ngAfterViewInit() {
   console.log("cardRef = ", this.card1);
   console.log("container = ", this.containerDiv);
}

app.component.html

<div class="product" #container>
   <product-card #cardRef></product-card>
</div>

2.) 基于引用查询。当您有多张卡片并且每张卡片都带有不同的数据集时,这很有用,以便在需要操作它们时进行查询。

app.component.ts

@ViewChild('cardRef1') card1: ProductCardComponent;
@ViewChild('cardRef2') card2: ProductCardComponent;

ngAfterViewInit() {
   console.log("cardRef1 = ", this.card1);
   console.log("cardRef2 = ", this.card2);
}

app.component.html

<div class="product">
   <product-card #cardRef1 [course]="course[0]"></product-card>
   <product-card #cardRef2 [course]="course[1]"></product-card>
</div>

3.) 当你需要查询一系列集合时,你可以使用@ViewChildren()装饰器。

app.component.ts

@ViewChildren(ProductCardComponent) cards: QueryList<ProductCardComponent>; //QueryList will give a lot methods embedded in it (e.g. first, last, forEach, etc)

ngAfterViewInit() {
   console.log(this.cards.first);  //It will give the object for the first card
}

app.component.html

<div class="product" #container>
   <product-card *ngFor="let product of products"></product-card>
</div>

我希望这能解决你的疑惑。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接