以下是一个使用Angular 9中的本地引用,#,视图子组件和@ViewChild的代码示例:
在父组件的HTML模板中,可以使用#来创建本地引用,并使用ViewChild来获取子组件的引用。
在父组件的TypeScript代码中,可以使用ViewChild来获取子组件的引用,并调用子组件的方法。
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: `...`,
})
export class ParentComponent {
@ViewChild('childComponent', { static: false }) childComponent: ChildComponent;
callChildComponentMethod() {
this.childComponent.childMethod();
}
}
在子组件的TypeScript代码中,可以定义一个公共方法,该方法可以在父组件中被调用。
import { Component } from '@angular/core';
@Component({
selector: 'app-child',
template: `...`,
})
export class ChildComponent {
childMethod() {
console.log('子组件方法被调用');
}
}
以上示例演示了如何使用本地引用,#,视图子组件和@ViewChild来在父组件中调用子组件的方法。