Вы можете использовать взаимодействие компонентов через сервис .
Компонент А:
@Component({
selector: 'app-a',
template: `
<h1>A</h1>
<p *ngFor="let item of dat">{{item}}</p>
<button type="button" (click)="addNumber()">Add Number</button>
`,
})
export class AComponent implements OnInit {
dat: Array<number> = [1, 2, 3];
count: number;
constructor(private service: AppService){}
ngOnInit(){
this.count = 3;
}
addNumber(){
this.count++;
this.dat.push(this.count);
this.service.addNewValue(this.count);
}
}
Компонент B:
@Component({
selector: 'app-b',
template: `
<h1>B</h1>
<p *ngFor="let item of dat">{{item}}</p>
`,
})
export class BComponent {
dat: Array<number> = [1, 2, 3];
subscription: Subscription;
constructor(private service : AppService){
this.subscription = this.service.newValue$.subscribe((res)=>{
this.dat.push(res);
})
}
}
Сервис:
export class AppService {
private newValue = new Subject<number>();
newValue$ = this.newValue.asObservable();
constructor(private http: HttpClient) { }
// Service message commands
addNewValue(value: number) {
this.newValue.next(value);
}
}
Демонстрация: Stackblitz