|
| 1 | +import "@angular/compiler"; |
| 2 | + |
| 3 | +import { TitleCasePipe } from "@angular/common"; |
| 4 | +import { httpResource } from "@angular/common/http"; |
| 5 | +import { |
| 6 | + Component, |
| 7 | + computed, |
| 8 | + inject, |
| 9 | + Injectable, |
| 10 | + type Signal, |
| 11 | + signal, |
| 12 | +} from "@angular/core"; |
| 13 | +import { Field, form } from "@angular/forms/signals"; |
| 14 | +import { bootstrapApplication } from "@angular/platform-browser"; |
| 15 | + |
| 16 | +@Injectable({ providedIn: "root" }) |
| 17 | +class AppService { |
| 18 | + static readonly #urlBase = "https://jsonplaceholder.typicode.com"; |
| 19 | + |
| 20 | + getUsers() { |
| 21 | + return httpResource(() => `${AppService.#urlBase}/users`); |
| 22 | + } |
| 23 | + |
| 24 | + getPosts(userIdSignal: Signal<string | undefined>) { |
| 25 | + return httpResource(() => { |
| 26 | + const userId = userIdSignal(); |
| 27 | + if (userId == undefined) return undefined; |
| 28 | + return { |
| 29 | + url: `${AppService.#urlBase}/posts`, |
| 30 | + params: { userId }, |
| 31 | + }; |
| 32 | + }); |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +@Component({ |
| 37 | + selector: "app-root", |
| 38 | + imports: [Field, TitleCasePipe], |
| 39 | + template: ` |
| 40 | + <h1>Buildless Angular 21 app</h1> |
| 41 | + @if (users.hasValue()) { |
| 42 | + <label> |
| 43 | + Select User: |
| 44 | + <select [field]="form.selectedUserId"> |
| 45 | + @for (user of users.value(); track user.id) { |
| 46 | + <option value="{{ user.id }}"> |
| 47 | + @{{ user.username }}: {{ user.name }} |
| 48 | + </option> |
| 49 | + } |
| 50 | + </select> |
| 51 | + </label> |
| 52 | + } @else if (users.isLoading()) { |
| 53 | + <p>Loading Users...</p> |
| 54 | + } |
| 55 | + @if (posts.hasValue()) { |
| 56 | + <ul> |
| 57 | + @for (post of posts.value(); track post.id) { |
| 58 | + <li>{{ post.title | titlecase }}</li> |
| 59 | + } |
| 60 | + </ul> |
| 61 | + } @else if (posts.isLoading()) { |
| 62 | + <p>Loading Posts...</p> |
| 63 | + } @else if (users.hasValue()) { |
| 64 | + <p>Select User to view posts</p> |
| 65 | + } |
| 66 | + <p> |
| 67 | + Data Source: |
| 68 | + <a href="https://jsonplaceholder.typicode.com/" target="_blank"> |
| 69 | + JSONPlaceholder |
| 70 | + </a> |
| 71 | + </p> |
| 72 | + `, |
| 73 | +}) |
| 74 | +class App { |
| 75 | + readonly #formState = signal({ selectedUserId: "" }); |
| 76 | + |
| 77 | + protected readonly form = form(this.#formState); |
| 78 | + protected readonly users = inject(AppService).getUsers(); |
| 79 | + protected readonly posts = inject(AppService).getPosts( |
| 80 | + computed(() => this.#formState().selectedUserId || undefined), |
| 81 | + ); |
| 82 | +} |
| 83 | + |
| 84 | +await bootstrapApplication(App); |
0 commit comments