问题描述
我正在处理一个模板,其中有一个子组件来显示父组件的详细信息。有一个服务调用,它提取项目列表中的数据,然后对其进行处理。但是,子组件所需的数据已在父控制器中可用。
我正在使用mat-expansion面板(来自Angular材质:https://material.angular.io/components/expansion/overview)来构建父组件的UI,并显示该项(子组件)的详细描述。
我面临的问题是,我正在使用mat-expansion-panel中的(已打开)事件发射器来更新要转发给子级的数据的绑定。当用户在扩展面板上单击时,将调用一个方法来提取数据,然后调用第二个服务以合并一些数据,然后将其发送到子组件进行渲染。我面临的问题是,尽管父组件正确转发了子组件中的值,但它们没有得到更新。但是,如果我使用超时,则绑定将在视图上更新。
将首先显示第一个绑定数据,这与预期的一样,但是展开时第二个项目数据仍将显示第一个项目数据。
以下是父组件:
<mat-accordion *ngFor="let item of items">
<mat-expansion-panel (opened)="getItemDetails()">
<mat-expansion-panel-header>
{{item.name}}
</mat-expansion-panel-header>
</mat-expansion-panel>
<ng-template matExpansionPanelContent>
<child-component *ngIf="dataTodisplay" [dataTodisplay]="dataTodisplay"></child-component>
</ng-template>
</mat-accordion>
父控制器:
@Component({
selector: 'parent-component',templateUrl: './parent.component.html'
})
export class ParentComponent implements OnInit {
items: any = [];
dataTodisplay: any;
constructor(private myService: MyService,private mySecondService: MySecondService){}
ngOnInit(): void {
this.myService.getItems().pipe(take(1)).subscribe((response) => {
this.items = response;
});
}
getItemDetails(item): void {
if (this.items) {
this.mySecondService.getMergedData(item).pipe(take(1)).subscribe((response) => {
// the below code update the child component bindings
this.dataTodisplay = {
emailId: response.emailId,phoneNumber: response.phoneNumber
};
// the same code works when placed inside setTimeout
setTimeout(() => {
this.dataTodisplay = {
emailId: response.emailId,phoneNumber: response.phoneNumber
};
});
});
}
}
}
子组件:
<div>
<p>{{dataTodisplay.emailId}}</p>
<p>{{dataTodisplay.phoneNumber}}</p>
</div>
子控制器:
@Component({
selector: 'child-component',templateUrl: './child.component.html'
})
export class ChildComponent implements OnInit {
@Input
dataTodisplay: any;
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)