angular - 输入属性绑定仅在超时后获取更改
问题描述
我正在开发一个模板,其中我有一个子组件来显示父组件的详细信息。有一个服务调用会提取项目列表的数据,然后对其进行处理。但是,子组件所需的数据已经在父控制器中可用。
我正在使用 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;
}
请让我知道代码是否有任何问题或是否有任何解决方法。谢谢。
解决方案
推荐阅读
- angular - 异步管道传递的角度输入数据在子组件中为空,但在父组件中不为空
- python - 是否有一种非循环方式来查找范围内的值,然后从列表中附加数据?
- oracle - 插入触发器之前的行级别
- c# - 如何在 keras.net 中设置 like-"gpu_options.allow_growth=true"?
- java - 基于另一个 ArrayList 添加或更新 ArrayList 的元素
- python - 将数据从 Excel sheet1 映射到 sheet2 在 python 中创建重复列
- python - Pandas merge_asof 显示两个数据框的日期
- kotlin - Kotlin 构造函数重载
- java - 如何设置线视图集监听器
- vba - 我的程序结构不正确 新手