1.父组件通过局部变量获取子组件引用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import { Component, OnInit, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'child-component', templateUrl: './child.component.html', styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit { ngOnInit (): void { console.log('child-component init'); } @Output() clickEvent = new EventEmitter<boolean>();
clickHandler(): void { this.clickEvent.emit(); } }
<button (click)="clickHandler()">child click</button>
|
假如super组件使用了child组件的话,(super组件以及child组件都在同一个模块中使用declarations引入了进来的话)那么使用局部变量的形式进行组件交互的话将会是下面这一种形式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <div> <span>{{count}}</span> <child-component (clickEvent)="addCount()" #child></child-component> <button (click)="child.clickHandler()">super click</button> </div>
import { Component } from '@angular/core';
@Component({ selector: 'super-component', templateUrl: './super.component.html', styleUrls: ['./super.component.css'] }) export class SuperComponent { private count: number = 1; private addCount = () => { this.count++; }; }
|
在上面这个例子中,点击子组件的button和super组件的button都能够达到同一个效果。分别使用的是方法绑定方案和局部变量方案。需要注意的是,使用局部变量只能调用子组件的公开属性以及方法,并且局部变量只能在模板视图中进行使用。
2.ViewChild方法
使用局部变量的局限性之一就是局部变量只能够在模板视图中进行使用,而在很多时候是有受限场景的,为此angular提供了ViewChild方法,它能够将子组件实例化一个实例进行使用,具体使用方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| <div> <span>{{count}}</span> <child-component (clickEvent)="addCount()" #child></child-component> <button (click)="myClick()">super click</button> </div>
import { Component, ViewChild } from '@angular/core';
@Component({ selector: 'super-component', templateUrl: './super.component.html', styleUrls: ['./super.component.css'] }) export class SuperComponent { @ViewChild(ChildComponent) cc: ChildComponent; private count: number = 1; private addCount: () => void = () => { this.count++; } private myClick: () => void = () => { this.cc.clickHandler(); } }
|