angularjs5 子组件中获得父组件的引用
时间: 2023-11-24 15:08:37 浏览: 34
在 AngularJS 5 中,可以通过使用 `@Input()` 装饰器将父组件的引用传递给子组件。具体步骤如下:
1. 在子组件的 TypeScript 文件中,定义一个带有 `@Input()` 装饰器的属性,用于接收父组件的引用。例如:
```
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: '<p>Child component</p>'
})
export class ChildComponent {
@Input() parentRef: any;
}
```
2. 在父组件的 HTML 文件中,使用子组件并传递父组件的引用。例如:
```
<app-child [parentRef]="this"></app-child>
```
这里将 `this` 作为父组件的引用传递给了子组件。
3. 在子组件中即可通过 `parentRef` 属性访问父组件的属性和方法。