我有父组件,有一个ng模板部分。在该ng模板部分下有一个子组件。现在我想使用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
:的使用
看到它在这里工作。
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');
}
}