拆分组件是一项必须的编程技能,符合高内聚低耦合的设计理念。
父子组件通信
父组件
father.html:
<div class="cont">
<button (click)="handleSceneZip()"></button>
......
</div>
<!--子组件-->
<app-child #imszip [id]="id" (removeloadingevt)="cancelLoading($event)"></app-child>
father.ts:
import { Component, Inject, OnDestroy, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-father',
templateUrl: './father.component.html',
styleUrls: ['./father.component.scss']
})
export class FatherComponent implements OnInit, OnDestroy {
@ViewChild('imszip') imszip;//子组件
id: number;
imploading: boolean;
constructor() {
this.id = 123;
this.imploading = false;
}
cancelLoading(evt) {//父组件接受子组件的反馈信息
console.log('父组件接受的信息>>>', evt);
if (evt === 'ok') {
this.imploading = false;
} else {
this.imploading = true;
}
}
handleSceneZip() {
this.imszip.doSceneZip();//调用子组件的方法
}
}
子组件
child.ts:
import { Component, OnInit, OnDestroy, ChangeDetectorRef,Input,Output,EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit, OnDestroy {
@Input() id:number;//接收父组件的属性信息
@Output() private removeloadingevt = new EventEmitter();//反馈到父组件的信息,名字跟父组件的方法名一致
constructor() {
}
doSceneZip(){
console.log('子组件实现的逻辑');
}
doSth(){
this.removeloadingevt.emit('ok');//发送给父组件
}
}
组件间通信
如果是没有关系的组件之间通信(比如兄弟组件),我们可以建一个公用的service,通过共享subject的方式实现通信。
service
import { Injectable } from "@angular/core";
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class CommonshareService {
public exportSceneSub$ = new Subject();//用于两个组件之间的信息共享
constructor() { }
}
A组件
import { Component, OnInit, OnDestroy} from '@angular/core';
import { CommonshareService } from 'src/app/service/commonshare.service';
@Component({
selector: 'app-a',
templateUrl: '.a.component.html',
styleUrls: ['./a.component.scss']
})
export class AComponent implements OnInit, OnDestroy {
constructor(public commonshareService: CommonshareService) {
}
doSth(){
this.commonshareService.next({id:123});//发布
}
}
B组件
import { Component, OnInit, OnDestroy} from '@angular/core';
import { CommonshareService } from 'src/app/service/commonshare.service';
@Component({
selector: 'app-b',
templateUrl: '.a.component.html',
styleUrls: ['./a.component.scss']
})
export class BComponent implements OnInit, OnDestroy {
public exsceneSub: any;
constructor(public commonshareService: CommonshareService) {
this.exsceneSub = this.commonshareService.exportSceneSub$.subscribe(scene => {
if (scene) {
this.doSth(scene);
}
});
}
doSth(scene){
console.log('做一些事情');
}
ngOnDestroy(): void {
this.exsceneSub.unsubscribe(); //释放句柄
}
}
网友评论