我们可以通过以下三种方式来实现:
- 传递一个组件的引用给另一个组件
- 通过子组件发送EventEmitter和父组件通信
- 通过serive通信
1. 传递一个组件的引用给另一个组件
模板引用变量通常用来引用模板中的某个 DOM 元素,它还可以引用 Angular 组件或指令或Web Component。
使用井号 (#) 来声明引用变量。 #phone 的意思就是声明一个名叫 phone 的变量来引用 元素
这种方式适合组件间有依赖关系。 app component
<app-side-bar-toggle [sideBar]="sideBar"></app-side-bar-toggle> <app-side-bar #sideBar></app-side-bar>
@Component({
selector: 'app-side-bar-toggle',
templateUrl: './side-bar-toggle.component.html',
styleUrls: ['./side-bar-toggle.component.css']
})
export class SideBarToggleComponent {
@Input() sideBar: SideBarComponent;
@HostListener('click')
click() {
this.sideBar.toggle();
}
}
@Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { sideBarIsOpened = false; toggleSideBar(shouldOpen: boolean) { this.sideBarIsOpened = !this.sideBarIsOpened; } }
2. 通过子组件发送EventEmitter和父组件通信
Demo2 这种方式利用事件传播,需要在子组件中写 app.component.html
<app-side-bar-toggle (toggle)="toggleSideBar()"></app-side-bar-toggle> <app-side-bar [isOpen]="sideBarIsOpened"></app-side-bar>
@Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { sideBarIsOpened = false; toggleSideBar(shouldOpen: boolean) { this.sideBarIsOpened = !this.sideBarIsOpened; } }
@Component({ selector: 'app-side-bar-toggle', templateUrl: './side-bar-toggle.component.html', styleUrls: ['./side-bar-toggle.component.css'] }) export class SideBarToggleComponent { @Output() toggle: EventEmitter<null> = new EventEmitter(); @HostListener('click') click() { this.toggle.emit(); } }
@Component({ selector: 'app-side-bar', templateUrl: './side-bar.component.html', styleUrls: ['./side-bar.component.css'] }) export class SideBarComponent { @HostBinding('class.is-open') @Input() isOpen = false; }
3. 通过service进行通信
Demo3 这里需要新建side-bar.service,我们把toggle方法写到service文件中, 然后将service注入到side-bar-toggle.component和side-bar-toggle.component,前者调用toggle方法,发送事件流,后者订阅事件
<app-side-bar-toggle></app-side-bar-toggle> <app-side-bar></app-side-bar>
@Component({ selector: 'app-side-bar-toggle', templateUrl: './side-bar-toggle.component.html', styleUrls: ['./side-bar-toggle.component.css'] }) export class SideBarToggleComponent { constructor( private sideBarService: SideBarService ) { } @HostListener('click') click() { this.sideBarService.toggle(); } }
@Component({ selector: 'app-side-bar', templateUrl: './side-bar.component.html', styleUrls: ['./side-bar.component.css'] }) export class SideBarComponent { @HostBinding('class.is-open') isOpen = false; constructor( private sideBarService: SideBarService ) { } ngOnInit() { this.sideBarService.change.subscribe(isOpen => { this.isOpen = isOpen; }); } }
@Injectable() export class SideBarService { isOpen = false; @Output() change: EventEmitter<boolean> = new EventEmitter(); toggle() { this.isOpen = !this.isOpen; this.change.emit(this.isOpen); } }