在Angular 9中,组件之间的互动可以通过多种方式实现,包括父组件向子组件传递数据、子组件向父组件传递数据以及通过共享服务实现组件之间的通信。下面将提供几种解决方法的代码示例。
父组件模板(parent.component.html):
父组件代码(parent.component.ts):
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
parentData: string = "Hello from parent component!";
}
子组件代码(child.component.ts):
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() data: string;
}
子组件代码(child.component.ts):
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Output() dataEvent = new EventEmitter();
sendDataToParent() {
this.dataEvent.emit("Hello from child component!");
}
}
子组件模板(child.component.html):
父组件模板(parent.component.html):
父组件代码(parent.component.ts):
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
receiveDataFromChild(data: string) {
console.log("Data received from child component:", data);
}
}
共享服务代码(shared.service.ts):
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SharedService {
private dataSubject = new BehaviorSubject("");
setData(data: string) {
this.dataSubject.next(data);
}
getData() {
return this.dataSubject.asObservable();
}
}
父组件代码(parent.component.ts):
import { Component, OnInit } from '@angular/core';
import { SharedService } from '../shared.service';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
parentData: string = "Hello from parent component!";
constructor(private sharedService: SharedService) { }
ngOnInit() {
this.sharedService.setData(this.parentData);
}
}
子组件代码(child.component.ts):
import { Component, OnInit } from '@angular/core';
import { SharedService } from '../shared.service';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
childData: string;
constructor(private sharedService: SharedService) { }
ngOnInit() {