子组件Input()加载时数据未定义
我有一个父组件,需要加载多个子组件。子组件将通过从父组件获取对象来加载,到目前为止其工作正常。但这里的问题是,我有一个要在子组件中渲染的按钮,并且按钮的文本来自父组件。如果我单击该按钮,相应的子组件应该打开,并且来自父组件的数据应该显示在子组件中,每当我单击子组件按钮时,子组件就会打开,但是 input( )
数据变得不确定。因此,当子组件展开时,父组件中的数据不会显示在子组件中。以下是示例代码 :
parentcompoent.html :
<div *ngFor="let tile of tiles$ | async;">
<ng-container [ngTemplateOutlet]="$any(getSelectedComponentTemplete(tile.tileUrl))"
[ngTemplateOutletContext]="{ $implicit: {data:tile} }">
</ng-container>
</div>
<ng-template #card let-obj>
<app-child [data]="obj.data"></app-child>
</ng-template>`
parentcomponent.component.ts :
@ViewChild('card', { static: true }) card!: TemplateRef<any>;
getSelectedComponentTemplete(type: string) {
switch (type) {
case "card":
return this.card;
default:
return;
}
childcomponent.html:
<mat-card>
<mat-card-title>
<button [routerLink]="data?.cardUrl" [disableRipple]="true" mat-flat-button>{{data?.tileName}}</button>
</mat-card-title>
</mat-card>`
childcomponent。 component.ts :
@Input()
data!: any;
ngOnInit(): void {
console.log(this.data);
}
我不知道为什么当子组件是父组件的一部分时它会完美加载,而当我单击子组件中的按钮时它不会加载数据。
有人可以帮我解决这个问题吗?
I have a parent component and that needs to be loaded multiple child components. The child components are to be loaded by taking the object from parent, so far its working as expected. But the problem here is, I have a button to be rendered in the child component and the text of the button comes from parent component. If I click on that button the respective child component should open and the data which came from parent component should be shown in the child component, here whenever I click on child component button, the child component is getting opened but the input()
data is getting undefined. Because of this the data from the parent component is not displaying in the child component when it is expanded. Here is the sample code :
parentcompoent.html :
<div *ngFor="let tile of tiles$ | async;">
<ng-container [ngTemplateOutlet]="$any(getSelectedComponentTemplete(tile.tileUrl))"
[ngTemplateOutletContext]="{ $implicit: {data:tile} }">
</ng-container>
</div>
<ng-template #card let-obj>
<app-child [data]="obj.data"></app-child>
</ng-template>`
parentcomponent.component.ts :
@ViewChild('card', { static: true }) card!: TemplateRef<any>;
getSelectedComponentTemplete(type: string) {
switch (type) {
case "card":
return this.card;
default:
return;
}
childcomponent.html :
<mat-card>
<mat-card-title>
<button [routerLink]="data?.cardUrl" [disableRipple]="true" mat-flat-button>{{data?.tileName}}</button>
</mat-card-title>
</mat-card>`
childcomponent.component.ts :
@Input()
data!: any;
ngOnInit(): void {
console.log(this.data);
}
I don't know why its loading perfectly when the child component is part of parent component and its not loading data when I click on the button in child component.
Can someone help me on this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论