【问题标题】:Angular 8 how to pass data between three componentsAngular 8如何在三个组件之间传递数据
【发布时间】:2023-03-09 03:00:02
【问题描述】:

我需要从祖父母 -> 父母 -> 子组件传递数据。

这是祖父母的html

<p>
Grant
<app-parent [child]="child" [other]="other"></app-parent>
</p>

Gratnt.ts

other = [{'name': 'abcd', age: 21},{'name': 'pqrs', age: 22}];    
child = [];
    getData() {
    this.service().subscribe((res)=>{
    this.child = res; })

父 html

<p>
Parent
<app-table [child]="newKid" [other]="newKid2"></app-table>
</p>

父.ts

@Input child = [];
@Input other = [];
newKid = [];
newKid2 = [];
process() {
//Process Data
this.newKid = this.child;
this.newKid2 = this.other;
}

table.html

<table>
<thead>
<tr *ngFor="let item of child"></tr>
</thead>
<tbody><tr *ngFor="let item of other"></tr></tbody>
</table>

table.ts

@Input child = [];
@Input other = [];

我的问题是如何将数据传输到嵌套链组件。?

【问题讨论】:

  • 那么你需要知道如何在三个子组件之间传递数据还是你想知道如何从祖父母->父母->孩子之间传递数据?
  • 我们无法将数据传递给链组件,而不是创建服务。
  • 从祖父母 -> 父母 -> 孩子传递数据
  • @Input() 不起作用?

标签: angular


【解决方案1】:

您可以使用Subjectrxjs中提供的@

GrandParent.component.html

<app-parent [parentSubject]="parentSubject.asObservable()"></app-parent>

GrandParent.component.ts

@Output() parentSubject: Subject<boolean> = new Subject<boolean>(true);
clickEvent(){
   this.parentSubject.next(true);
}

Parent.Component.html

<app-child [childSubject]="childSubject.asObservable()"></app-child>

Parent.Component.ts

@Input() parentsubject: Subject<boolean> = new Subject<boolean>(true);
@Output() childSubject: Subject<boolean> = new Subject<boolean>(true);

this.parentsubject.subscribe(res=> {
   this.childSubject.next(res);
})

Child.Component.html

<div></div>

Child.Component.ts

@Input() childSubject: Subject<boolean> = new Subject<boolean>();
this.childSubject.subscribe(res => {
  Console.log(res);
});

希望这会有所帮助。干杯:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-22
    • 2020-10-10
    • 2017-08-12
    • 1970-01-01
    • 2019-12-26
    • 2017-01-12
    相关资源
    最近更新 更多