如何解决在 Angular 中使用 ViewChild 访问驻留在 ng-component 下的子组件
我有父组件,有一个 ng-template 部分。在这个 ng-template 部分下有一个 子组件。现在我想使用 ViewChild 装饰器访问这个子组件。使用 ViewChild 后,我想执行该子组件的功能。但它不起作用。代码如下:
<ng-template #mymodal let-modal>
<div class="modal-header">
<h4 class="modal-title" id="modal-basic-title">Bootstrap Modal</h4>
<button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<app-expense-head #child></app-expense-head>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-dark" (click)="modal.close('Save click')">Ok</button>
<button type="button" class="btn btn-outline-dark" (click)="onClickCancel()">Cancel</button>
</div>
</ng-template>
TS 文件代码
@ViewChild(ExpenseHeadComponent,{ static: false }) childExpenseHead: ExpenseHeadComponent;
onClickCancel() {
this.childExpenseHead.myAlert();
}
解决方法
尝试访问 ngAfterViewInit() { }
生命周期挂钩上的子值。
您已经使用 #child 在 child 中添加了模板引用。因此,在模板中,您可以使用以下引用访问 child 中的公共方法
(click) ="child.myAlert()"
,
它可以从类代码中工作。请参阅下面的示例,该示例在结构上与您的代码类似,并注意 ngAfterViewInit
和 ViewChild
的使用:
看到它工作here。
HTML(父组件)
<ng-template #myTemplate>
<hello name="{{ name }}"></hello>
</ng-template>
<button (click)="clickChild()">Call Child</button>
TS(父组件)
import { AfterViewInit,Component,EmbeddedViewRef,OnInit,TemplateRef,VERSION,ViewChild,ViewContainerRef } from '@angular/core';
import { HelloComponent } from './hello.component';
@Component({
selector: 'my-app',templateUrl: './app.component.html',styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit,AfterViewInit {
@ViewChild(HelloComponent,{ static: false }) child: HelloComponent;
@ViewChild('myTemplate',{ static: false,read: TemplateRef }) myTemplate: TemplateRef<any>;
name = 'Angular ' + VERSION.major;
constructor(private viewContainerRef: ViewContainerRef) {}
ngOnInit(): void {
}
ngAfterViewInit(): void {
const embeddedViewRef = this.viewContainerRef.createEmbeddedView(this.myTemplate);
embeddedViewRef.detectChanges();
}
clickChild(): void {
this.child.myAlert();
}
}
HTML 和 ts(子组件)
import { Component,Input } from '@angular/core';
@Component({
selector: 'hello',template: `<h1>Hello {{name}}!</h1>`,styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@Input() name: string;
myAlert(): void {
console.log('in hello component');
alert('alert child');
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。