Issue
I am facing an issue while trying to render a child component using data from a Observable from it's parent, and after that, using async pipe
to convert the data to a list objects and render it using *NgFor. I did:
Generate Observable Data in Parent Component:
// Parent Component dataSet$!: Observable<Data[]>; ngOnInit() { this.dataSet$ = this.serviceData.getData(); }
Send Data from Parent to Child Using Async Pipe:
<!-- Parent Component Template --> <ng-container *ngIf="dataSet$ | async as dataSet"> <app-row-data-list *ngFor="let data of dataSet" [data]="data"></app-row-data-list> </ng-container>
Child Component with @Input Property:
// Child Component export class RowDataListComponent { @Input() data!: Data; }
However, the data is not being rendered as expected. The child components do not appear.
What I tried so far is the fixes mentioned in the following answers:
- https://stackoverflow.com/a/76025282/8297745
- https://stackoverflow.com/a/50586048/8297745
- https://stackoverflow.com/a/73599001/8297745
But I was'nt able to fix it using those. I also searched a lot. Actually, I'm a couple of hours on this so if someone could help me.
Thanks a lot.
Edit: With help from the answer here, I was able to fix it. I did as follows (Look in Stack Blitz example):
https://angular-child-parent-communication-example-uxz7dg.stackblitz.io
Solution
I am not sure what is your exact code but here you can see a working exapmple:
interface Item {
userId: number;
id: number;
title: string;
completed: boolean;
}
type Items = Item[];
@Injectable({ providedIn: 'root' })
class DataService {
private http = inject(HttpClient);
getData() {
return this.http.get<Items>(`https://jsonplaceholder.typicode.com/todos`);
}
}
@Component({
selector: 'app-child',
standalone: true,
template: `
<pre>{{item() | json}}</pre>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [JsonPipe],
})
export class ChildComponent {
item = input<Item>();
}
@Component({
selector: 'app-root',
standalone: true,
template: `
<h1>Hello from {{ name }}!</h1>
<app-child *ngFor="let data of (data$ | async)" [item]="data"></app-child>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [ChildComponent, NgFor, AsyncPipe],
})
export class App {
name = 'Angular';
private dataService = inject(DataService);
data$ = this.dataService.getData().pipe(startWith([]), share());
}
bootstrapApplication(App, { providers: [provideHttpClient()] });
See stackblitz
Answered By - NgDaddy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.