How are you calculating averages in Angular templates today? {{ reviews | average:'rating' }} One pipe. No component logic. No computed properties. Works with primitives and object arrays: {{ [85, 92, 67, 94, 71] | average }} → 81.8 {{ students | average:'grade' }} → class average {{ data | average:'metrics.score' }} → nested paths too npm i ngx-transforms https://lnkd.in/dRYZts_V #Angular #TypeScript #WebDev #ngxTransforms
More Relevant Posts
-
Understanding Generics in Angular (TypeScript) ❌ Writing separate logic for each data type? ❌ Repeating the same code again and again? Generics are one of the most powerful features in TypeScript. They help you write flexible, reusable, and type-safe code without being tied to a specific data type. 👉 Write once… use for any type. Example: function getData(data: T): T { return data; } Now it works for everything: ✔ string ✔ number ✔ boolean ✔ objects 🔥 Real Angular example: this.http.get<User[]>('/api/users') That <User[]> is a Generic — it tells Angular what data to expect from the API. This improves type checking and reduces runtime errors. 💡 Why Generics matter: ✅ Type safety ✅ Reusable code ✅ Cleaner architecture Generics may look simple… but they have a BIG impact on building scalable Angular applications 🚀 #Angular #TypeScript #Frontend #WebDevelopment #CodingTips
To view or add a comment, sign in
-
-
𝗜 𝘀𝗽𝗲𝗻𝘁 𝟰 𝗵𝗼𝘂𝗿𝘀 𝗱𝗲𝗯𝘂𝗴𝗴𝗶𝗻𝗴 𝗮 "𝗴𝗵𝗼𝘀𝘁 𝗨𝗜" — 𝗰𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁𝘀 𝘁𝗵𝗮𝘁 𝗿𝗲𝗳𝘂𝘀𝗲𝗱 𝘁𝗼 𝘂𝗽𝗱𝗮𝘁𝗲 𝗼𝗻𝗹𝘆 𝘁𝗼 𝗿𝗲𝗮𝗹𝗶𝘀𝗲 𝗜 𝗰𝗮𝘂𝘀𝗲𝗱 𝗶𝘁 𝗺𝘆𝘀𝗲𝗹𝗳. 1. We had a real-time dashboard in Angular showing live sensor data. Product was happy. QA was happy. Then staging broke. 2. 𝗥𝗼𝘄𝘀 𝘄𝗲𝗿𝗲𝗻'𝘁 𝗿𝗲-𝗿𝗲𝗻𝗱𝗲𝗿𝗶𝗻𝗴 𝗮𝗳𝘁𝗲𝗿 𝗱𝗮𝘁𝗮 𝘂𝗽𝗱𝗮𝘁𝗲𝘀. The array was clearly mutating in the console. The template just… didn't care. 3. I'd switched the component to ChangeDetectionStrategy.OnPush for "performance" — without understanding what that actually means. 𝗧𝗵𝗲 𝗺𝗶𝘀𝘁𝗮𝗸𝗲: ❌ Mutating the array directly — OnPush never sees this this.sensors.push(newSensor); this.sensors[0].value = 99; With OnPush, Angular only checks a component when its input reference changes — not when you mutate the object inside it. 𝗧𝗵𝗲 𝗳𝗶𝘅: ✅ Return a new reference — Angular picks it up instantly this.sensors = [...this.sensors, newSensor]; this.sensors = this.sensors.map((s, i) => i === 0 ? { ...s, value: 99 } : s ); Or — if you're already using signals in Angular 17+ — just use a signal() and skip this mental overhead entirely. 𝗧𝗵𝗲 𝗿𝗲𝗮𝗹 𝗹𝗲𝘀𝘀𝗼𝗻: OnPush is not a magic performance button. It's a contract you promise Angular you'll treat state as immutable. Break the contract, pay in ghost UIs. 𝗔𝗱𝗼𝗽𝘁 𝗶𝘁. 𝗟𝗼𝘃𝗲 𝗶𝘁. 𝗕𝘂𝘁 𝘂𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱 𝗶𝘁 𝗳𝗶𝗿𝘀𝘁. 𝗠𝘆 𝗾𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝘁𝗼 𝘆𝗼𝘂 → Have you ever turned on OnPush and immediately broken something? What was your "wait, THAT was the issue?" moment? Drop it below. 👇 #Angular #TypeScript #WebDevelopment #FrontendDevelopment #SoftwareEngineering #LearnInPublic #CodingMistakes
To view or add a comment, sign in
-
I just updated my 𝗘𝘀𝘀𝗲𝗻𝘁𝗶𝗮𝗹 𝗔𝗻𝗴𝘂𝗹𝗮𝗿 𝗦𝗶𝗴𝗻𝗮𝗹𝘀 𝗖𝗵𝗲𝗮𝘁𝘀𝗵𝗲𝗲𝘁 for 𝗔𝗻𝗴𝘂𝗹𝗮𝗿 𝟮𝟮. The signals ecosystem keeps growing and I wanted to make sure the cheatsheet reflects where things are today — from v16 all the way to v22. 𝗪𝗵𝗮𝘁'𝘀 𝗻𝗲𝘄: → 𝚍𝚎𝚋𝚘𝚞𝚗𝚌𝚎𝚍() is now included — Angular's first signal-native debouncing primitive. You give it a signal and a wait time, it gives you back a full 𝚁𝚎𝚜𝚘𝚞𝚛𝚌𝚎‹𝚃› with value, status, loading state, and error handling. No RxJS needed. Link to the full article (if you perfer medium check comments) 👇 https://lnkd.in/dezZdvCy ♻️ Repost if this is useful for your team. #angular #signals
To view or add a comment, sign in
-
isString & isNumber. Type-narrow unknown data right in your Angular templates. @if (cell | isNumber) { <td class="text-right">{{ cell }}</td> } @if (cell | isString) { <td>{{ cell }}</td> } Perfect for JSON walkers and dynamic table renderers. #Angular #TypeScript
To view or add a comment, sign in
-
Angular Day 6 - Routing, Pipes & Services in Action! In this session, I explored some of the most important concepts in Angular Routing, Pipes, and Services and implemented them in a single application. This felt like a major step towards building real-world Angular applications What I implemented: • Angular Routing using RouterModule and Routes • Navigation using routerLink and routerLinkActive • Dynamic page loading using router-outlet • Created multiple routes (Welcome, First, Second, Third, etc.) • Implemented a custom 404 Not Found page • Built a clean navigation bar with active state highlighting Pipes Implementation: • Used built-in pipes like uppercase, lowercase, titlecase, slice • Number, Date, Currency, and Percentage pipes • JSON pipe for object visualization • Async pipe with Observable data • Created a custom Reverse Pipe Services Implementation: • Created a reusable service using @Injectable • Implemented calculator logic inside a service • Used Dependency Injection (inject()) to access service • Performed operations like Add, Subtract, Multiply, Divide Key Highlights: • Smooth navigation between components without page reload • Clean URL-based routing structure • Real-time data transformation using pipes • Code reusability using services • Separation of concerns (UI, Logic, Navigation) Key Learning: This session gave me a clear understanding of how Angular applications are structured in real-world scenarios using routing, reusable logic (services), and data transformation (pipes). I’ve attached a demo video as proof of implementation. Grateful to our lecturer Ram Shankar Darivemula for delivering these concepts in a simple, clear, and practical manner. Excited to move forward and build more dynamic, scalable Angular applications! #Angular #Routing #AngularPipes #AngularServices #FrontendDevelopment #WebDevelopment #TypeScript #SoftwareEngineering #LearningJourney #css #html #Javascript #CodingJourney #DependencyInjection #SPA
To view or add a comment, sign in
-
Angular mistakes that look correct… but aren’t: --- → Multiple async pipes ✔ Looks fine ❌ Creates multiple subscriptions {{ users$ | async }} {{ users$ | async }} ✔ Fix (Option 1 — Signals): users = toSignal(this.users$); {{ users() }} {{ users() }} ✔ Fix (Option 2 — let syntax): <ng-container *ngIf="users$ | async as users"> {{ users }} {{ users }} </ng-container> --- → OnPush without immutability this.user().name = 'John'; ✔ Fix: this.user.set({ ...this.user(), name: 'John' }); --- → Derived state stored manually this.total = this.items.length; ✔ Fix: total = computed(() => this.items().length); --- → BehaviorSubject for local state count$ = new BehaviorSubject(0); ✔ Fix: count = signal(0); --- → Function in template {{ getTotal() }} ✔ Fix: total = computed(() => calculateTotal()); --- → Manual subscriptions this.api.get().subscribe(data => this.data = data); ✔ Fix: data = toSignal(this.api.get(), { initialValue: [] }); --- → Hidden vs ngIf <div [hidden]="isVisible"> ✔ Fix: <div *ngIf="isVisible"> --- Key takeaway: Angular gives multiple ways to solve the same problem. The difference is in scalability. Use patterns that reduce subscriptions, DOM, and change detection work. What pattern did you recently improve?
To view or add a comment, sign in
-
🚀 Angular Tip #1 — Stop Manual Subscriptions The tip shown is a solid Angular best practice. ❌ The Problem (Manual Subscribe) ngOnInit() { this.service.getData().subscribe(data => { // Do something with data }); } This approach has real issues: • Memory leaks — subscription stays alive after component destroy • Boilerplate — need ngOnDestroy + Subscription cleanup • Easy to forget — most Angular leaks come from this pattern ✅ The Solution (Async Pipe) data$ = this.service.getData(); {{ data$ | async }} Why this is better: • Auto unsubscribe when component is destroyed • Cleaner — no ngOnInit boilerplate • Works great with OnPush change detection • Angular manages subscription lifecycle 🔔 One nuance to keep in mind Async pipe is best when you're displaying data. If you need side effects in component, you may still use ".subscribe()" — but unsubscribe properly. Recommended approaches: • "takeUntilDestroyed()" (Angular 16+) — modern way • "takeUntil(destroy$)" with Subject • Manual ".unsubscribe()" in "ngOnDestroy" Small change. Big performance win. Follow for daily Angular tips 🔥 #Angular #TypeScript #RxJS #Frontend #WebDevelopment
To view or add a comment, sign in
-
-
Angular Signals — Overview of the new reactivity model With modern Angular, Signals introduce a simpler and more predictable way to manage state and reactivity. Here’s a structured overview of the key concepts: 1) signal() Used to create reactive state. const count = signal(0); - Read value: count() - Set value: count.set(1) - Update value: count.update(v => v + 1) --- 2) computed() Creates derived state based on other signals. const double = computed(() => count() * 2); - Automatically recalculates when dependencies change - No subscriptions required --- 3) effect() Used to handle side effects. effect(() => { console.log(count()); }); - Runs when dependent signals change - Should not be used for state derivation --- 4) Equality check Signals avoid unnecessary updates by comparing values. signal(initialValue, { equal: fn }); - Customize comparison logic if needed --- 5) untracked() Allows reading a signal without tracking it as a dependency. effect(() => { console.log(untracked(() => count())); }); - Useful for avoiding unwanted re-execution --- 6) linkedSignal() Used to link or derive state in more advanced scenarios. - Helps structure complex reactive relationships --- 7) Signals vs RxJS Signals: - Simpler state management - Synchronous reactivity RxJS: - Better for async streams - More powerful for complex flows Both can coexist depending on the use case. --- Conclusion: Signals are not a full replacement for RxJS, but they are becoming the standard for local state management in Angular applications. They improve readability, reduce boilerplate, and provide better performance in many scenarios. --- Are you using Signals in your projects yet?
To view or add a comment, sign in
-
-
🔀 ⁉️ Feel like your Angular component logic is drowning in a sea of if-else chains? #Day24 of #TypescriptBeforeAngular with SANDEEP KUMAR (#IAM5K): Discriminated Unions (The Tagged "Either/Or") You have a variable that can be one of several distinct states (A | B | C), and you end up writing massive conditional blocks to handle each possibility. This is a massive trap. It silences the compiler and makes it easy to create simple typos or, worse, to forget a case entirely. Today, we meet the absolute secret to clean and reliable logic: Discriminated Unions. 1️⃣ What are Discriminated Unions? In #TypeScript, you don’t always need a formal blueprint (like an Interface or a Class) to define an object’s structure. You can use a Discriminated Union (also called a "tagged" union) when you have a list of distinct types (Success | Error) that share one common property, known as the "tag" or "discriminant." This tag allows you to perform an authorized check to determine exactly which type you are working with in every branch of your switch statement. // Ssssh! The recipe: Both have a 'type' tag. interface Success { type: 'SUCCESS'; data: string; } interface Error { type: 'ERROR'; message: string; } // Combined, you get an explicit state bucket: type ApiResponse = Success | Error; function handleResponse(res: ApiResponse) { // TypeScript looks at the tag (the discriminant): switch (res.type) { case 'SUCCESS': return res.data; // TypeScript is certain this is Success bucket! case 'ERROR': return res.message; // TypeScript is certain this is Error bucket! } } 2️⃣ Significance in #Angular: Service callbacks using any, lead to confusing template errors because the component receiving data it didn't expect. In modern Angular (especially for state management and DOM interaction), Discriminated Unions are essential for creating reliably flexible components. Example: You can define a component’s input options with absolute precision: @Input() theme: 'primary' | 'secondary' | 'danger'; The compiler is now your safety net. If you try to use [theme]="'primery'" in your HTML template, TypeScript stops you immediately and says: "You made a typo! Check the allowed options." Discriminated Unions turn "I hope I am handling this right" into "I know I am handling this right." It is about building components that are not just typed, but truly truly safe. 💡 Beginner Tip: Think of Discriminated Unions as standardized labels for standardized data buckets. If you use them, you can build "exhaustive" checks (Day 10!) and prevent those annoying "unexpected value" errors that haunt every developer's nightmares. Use them to create predictable, smart components that can handle diverse data safely. 👉 What is the one tag property (type, status, kind) you use most often in your Angular project?👇 #WebDev #CodingTips #NewDeveloper #CleanCode #DiscriminatedUnions #Immutability #PredictableState #TypeSafety #Btech #Internship
To view or add a comment, sign in
-
-
Angular Signals + LocalStorage + BroadcastChannel = Pure Magic! ✨ Learn how to build a reactive persistence layer that syncs across tabs automatically. No more manual refreshes or complex RxJS streams for simple state sharing.
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
Great question! Using a pure pipe is usually the cleanest approach for calculated values in Angular templates, keeping change detection efficient and the template readable.