0

我正在 Angular 13 中创建应用程序。我想调用from 、 using的方法show(),但出现错误。在这种情况下,较旧的问题和答案不起作用。ChildComponentParentComponent@ViewChild

家长

<app-child #child></app-child>
@ViewChild('child') child: ChildComponent;

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

孩子

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

错误:

属性 'child' 没有初始化器,也没有在构造函数中明确分配。


解决方案1:

家长

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

错误:

TypeError:无法读取未定义的属性(读取“显示”)


解决方案2:

家长

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

没有错误 工作正常,但我怀疑这是否正确?

4

2 回答 2

1

你可以这样初始化。Ii 将帮助您解决您的错误。

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

or 

@ViewChild('child') child: ChildComponent = {} as ChildComponent;
于 2022-01-21T12:58:06.947 回答
1

解决您的疑问-

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');
}

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

有 3 种方法可以通过角度查询子组件、组件的子项或 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>

我希望这能消除你的疑问。

于 2022-01-21T13:53:28.460 回答