### Angular App Setup with NgRx and Routing Source: https://context7.com/nrwl/nx-examples/llms.txt Sets up an Angular application with NgRx for state management and Angular Router for navigation. This includes the main entry point, the App module, and the App component. ```typescript // Main entry point - apps/products/src/main.ts import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; platformBrowserDynamic() .bootstrapModule(AppModule) .catch((err) => console.error(err)); ``` ```typescript // App module - apps/products/src/app/app.module.ts import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouterModule } from '@angular/router'; import { StoreModule } from '@ngrx/store'; import { AppComponent } from './app.component'; import '@nx-example/shared/header'; import '@nx-example/shared/styles'; @NgModule({ declarations: [AppComponent], imports: [ BrowserModule, RouterModule.forRoot([ { path: '', pathMatch: 'full', loadChildren: () => import('@nx-example/products/home-page').then( (module) => module.ProductsHomePageModule ), }, { path: 'product', loadChildren: () => import('@nx-example/products/product-detail-page').then( (module) => module.ProductsProductDetailPageModule ), }, ], { initialNavigation: 'enabledBlocking' }), StoreModule.forRoot({}), ], bootstrap: [AppComponent], schemas: [CUSTOM_ELEMENTS_SCHEMA], }) export class AppModule {} ``` ```typescript // App component - apps/products/src/app/app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'nx-example-root', template: "\n ", }) export class AppComponent {} ``` -------------------------------- ### React App Setup with Routing Source: https://context7.com/nrwl/nx-examples/llms.txt Configures a React application using React Router for navigation and integrates shared components. This snippet includes the main entry point, the App component, and Webpack configuration for the React app. ```typescript // Main entry point - apps/cart/src/main.tsx import { StrictMode } from 'react'; import * as ReactDOM from 'react-dom/client'; import { BrowserRouter as Router } from 'react-router-dom'; import App from './app/app'; import '@nx-example/shared/styles'; const root = ReactDOM.createRoot( document.getElementById('root') as HTMLElement ); root.render( ); ``` ```typescript // App component - apps/cart/src/app/app.tsx import { Routes, Route, Link } from 'react-router-dom'; import { CartCartPage } from '@nx-example/cart/cart-page'; import '@nx-example/shared/header'; export function App() { return ( <> } /> } /> ); } export default App; ``` ```javascript // Webpack configuration - apps/cart/webpack.config.js const { composePlugins, withNx } = require('@nx/webpack'); const { withReact } = require('@nx/react'); module.exports = composePlugins(withNx(), withReact(), (config) => { return config; }); ``` -------------------------------- ### Nx Commands - Serve, Build, and Test Source: https://context7.com/nrwl/nx-examples/llms.txt Common Nx CLI commands for serving applications, building for production, and running unit tests. This covers both Angular and React applications, as well as shared libraries. ```bash # Serve applications nx serve products # Start Angular app on localhost:4200 nx serve cart # Start React app on localhost:4201 # Build for production nx build products --configuration=production nx build cart --configuration=production # Run tests nx test products # Jest unit tests for Angular app nx test cart # Jest unit tests for React app nx test shared-cart-state # Test shared cart state library ``` -------------------------------- ### Using TypeScript Path Aliases in Imports Source: https://context7.com/nrwl/nx-examples/llms.txt This example demonstrates how to import modules from different libraries within the Nx monorepo using the configured path aliases. It showcases the benefit of cleaner and more organized import statements. No specific dependencies are required beyond the TypeScript configuration. ```typescript // Usage in any TypeScript file import { CartCartPage } from '@nx-example/cart/cart-page'; import { Product } from '@nx-example/shared/product/types'; import { getProducts } from '@nx-example/shared/product/state'; import '@nx-example/shared/header'; ``` -------------------------------- ### Nx Commands - Generate Libraries, Lint, Format, and Deploy Source: https://context7.com/nrwl/nx-examples/llms.txt Nx CLI commands for generating new libraries (React and Angular), linting projects, formatting code, and deploying applications. These commands facilitate code generation, maintain code quality, and enable deployment. ```bash # Generate new library nx g @nx/react:lib my-lib --directory=libs/shared/my-lib nx g @nx/angular:lib my-angular-lib --directory=libs/products/my-lib # Lint and format nx lint products nx format:write # Format all files with Prettier # Deploy nx deploy products # Deploy products app to Netlify nx deploy cart # Deploy cart app to Netlify ``` -------------------------------- ### Nx Commands - E2E, Affected, and Dependency Graph Source: https://context7.com/nrwl/nx-examples/llms.txt Nx CLI commands for running end-to-end tests, executing commands only on affected projects, and visualizing the project dependency graph. These commands help optimize workflows and understand project relationships. ```bash # E2E testing nx e2e products-e2e # Cypress E2E tests for products app nx e2e cart-e2e # Cypress E2E tests for cart app # Affected commands (only test/build what changed) nx affected:test # Test only affected projects nx affected:build # Build only affected projects nx affected:lint # Lint only affected projects # Dependency graph nx dep-graph # View interactive dependency graph ``` -------------------------------- ### Framework-Agnostic Product Price Display using Web Components Source: https://context7.com/nrwl/nx-examples/llms.txt Implements a reusable product price display component using the Web Components API, making it framework-agnostic. It defines an `nx-example-product-price` custom element that takes a 'value' attribute for the price and formats it. Usage examples are provided for React, Angular, and vanilla JavaScript. ```typescript // Definition (in @nx-example/shared/product/ui) export class ProductPriceElement extends HTMLElement { static observedAttributes = ['value']; private get displayPrice(): string { return '$' + (this.value / 100).toFixed(2); } get value(): number { return +this.getAttribute('value'); } set value(price: number) { this.setAttribute('value', price.toString()); } attributeChangedCallback(name: string) { if (name === 'value') { this.textContent = this.displayPrice; } } } customElements.define('nx-example-product-price', ProductPriceElement); // React usage import '@nx-example/shared/product/ui'; function ProductCard({ product }) { return (

{product.name}

); } // Angular usage with CUSTOM_ELEMENTS_SCHEMA import '@nx-example/shared/product/ui'; @Component({ selector: 'app-product-card', template: `

{{ product.name }}

`, schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class ProductCardComponent { @Input() product: Product; } // Vanilla JavaScript usage const priceElement = document.createElement('nx-example-product-price'); priceElement.value = 10000; // $100.00 document.body.appendChild(priceElement); // Displays: $100.00 ``` -------------------------------- ### Shared Header Web Component Definition and Usage (TypeScript, React, Angular) Source: https://context7.com/nrwl/nx-examples/llms.txt Defines a reusable header web component using TypeScript, which can be integrated into various frameworks. It includes example usage within React and Angular applications, demonstrating how to import and utilize the custom element. ```typescript export class HeaderElement extends HTMLElement { static observedAttributes = ['title']; private titleElement = document.createElement('h2'); connectedCallback() { this.appendChild(this.createLeftSide()); this.appendChild(this.createRightSide()); } private createLeftSide() { const leftSide = document.createElement('div'); const homeLink = document.createElement('a'); const homeLinkText = document.createElement('h2'); homeLink.href = '/'; homeLinkText.textContent = 'Nx Store'; homeLink.appendChild(homeLinkText); leftSide.appendChild(homeLink); this.titleElement.textContent = this.getAttribute('title') || ''; leftSide.appendChild(this.titleElement); return leftSide; } private createRightSide() { const githubLink = document.createElement('a'); const icon = document.createElement('span'); githubLink.href = 'https://github.com/nrwl/nx-examples'; icon.classList.add('icon', 'icon-github'); githubLink.appendChild(icon); const rightSide = document.createElement('div'); rightSide.appendChild(githubLink); return rightSide; } get title(): string { return this.getAttribute('title') || ''; } set title(value: string) { this.setAttribute('title', value); } attributeChangedCallback() { this.titleElement.textContent = this.title; } } customElements.define('nx-example-header', HeaderElement); ``` ```typescript // React usage import '@nx-example/shared/header'; function App() { return ( <> } /> ); } ``` ```typescript // Angular usage import '@nx-example/shared/header'; @Component({ selector: 'app-root', template: ` `, schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class AppComponent { pageTitle = 'Product Catalog'; } ``` -------------------------------- ### Product State Management with NgRx and React Hooks Source: https://context7.com/nrwl/nx-examples/llms.txt Manages product catalog state using selectors for data retrieval. Supports both Angular with NgRx and React with hooks. Defines product types, data, and state selectors. Dependencies include '@nx-example/shared/product/types', '@nx-example/shared/product/data', and '@nx-example/shared/product/state'. ```typescript // Product types and data import { Product } from '@nx-example/shared/product/types'; import { products } from '@nx-example/shared/product/data'; import { getProducts, getProduct } from '@nx-example/shared/product/state'; // Product interface interface Product { id: string; name: string; image?: string; price: number; // in cents } // React usage import { useReducer } from 'react'; import { productsReducer, initialState } from '@nx-example/shared/product/state/react'; function ProductList() { const [productsState] = useReducer(productsReducer, initialState); const allProducts = getProducts(productsState); const specificProduct = getProduct(productsState, '1'); return ( ); } // Angular NgRx usage with observables import { Store, select } from '@ngrx/store'; import { getProductsState, getProducts } from '@nx-example/shared/product/state'; import { Component, inject } from '@angular/core'; import { Observable } from 'rxjs'; // Assuming ProductsPartialState is defined elsewhere interface ProductsPartialState {} @Component({ selector: 'app-product-list', template: ` @for (product of products | async; track product.id) {

{{ product.name }}

} ` }) export class ProductListComponent { private store = inject>(Store); products: Observable = this.store.pipe( select(getProductsState), select(getProducts) ); } ``` -------------------------------- ### TypeScript Path Mapping Configuration in tsconfig.base.json Source: https://context7.com/nrwl/nx-examples/llms.txt This JSON configuration defines TypeScript compiler options, specifically focusing on path mapping. It sets up aliases for various libraries within the Nx monorepo, enabling modular imports. Dependencies include the TypeScript compiler. It takes no direct input but influences the compilation process. ```json { "compileOnSave": false, "compilerOptions": { "rootDir": ".", "sourceMap": true, "declaration": false, "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "importHelpers": true, "target": "es2015", "module": "esnext", "lib": ["es2020", "dom"], "skipLibCheck": true, "skipDefaultLibCheck": true, "baseUrl": ".", "paths": { "@nx-example/cart/cart-page": ["libs/cart/cart-page/src/index.ts"], "@nx-example/products/home-page": ["libs/products/home-page/src/index.ts"], "@nx-example/products/product-detail-page": ["libs/products/product-detail-page/src/index.ts"], "@nx-example/shared/assets": ["libs/shared/assets/src/index.ts"], "@nx-example/shared/cart/state": ["libs/shared/cart/state/src/index.ts"], "@nx-example/shared/cart/state/react": ["libs/shared/cart/state/src/react.ts"], "@nx-example/shared/e2e-utils": ["libs/shared/e2e-utils/src/index.ts"], "@nx-example/shared/header": ["libs/shared/header/src/index.ts"], "@nx-example/shared/jsxify": ["libs/shared/jsxify/src/index.ts"], "@nx-example/shared/product/data": ["libs/shared/product/data/src/index.ts"], "@nx-example/shared/product/state": ["libs/shared/product/state/src/index.ts"], "@nx-example/shared/product/state/react": ["libs/shared/product/state/src/react.ts"], "@nx-example/shared/product/types": ["libs/shared/product/types/src/index.ts"], "@nx-example/shared/product/ui": ["libs/shared/product/ui/src/index.ts"], "@nx-example/shared/styles": ["libs/shared/styles/src/index.ts"] } } } ``` -------------------------------- ### Angular Product Detail Page: Module and Component Source: https://context7.com/nrwl/nx-examples/llms.txt Implements the Angular module and component for the product detail page. It fetches product information based on route parameters and uses NgRx selectors to retrieve specific product data. The component displays product details and includes an 'Add to Cart' functionality. ```typescript // Module definition import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule } from '@angular/router'; import { SharedProductStateModule } from '@nx-example/shared/product/state'; import '@nx-example/shared/product/ui'; @NgModule({ imports: [ CommonModule, SharedProductStateModule, RouterModule.forChild([ { path: ':productId', component: ProductDetailPageComponent }, ]), ], declarations: [ProductDetailPageComponent], schemas: [CUSTOM_ELEMENTS_SCHEMA], }) export class ProductsProductDetailPageModule {} // Component implementation import { Component, inject } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Store, select } from '@ngrx/store'; import { Observable } from 'rxjs'; import { map, concatMap } from 'rxjs/operators'; import { getProductsState, getProduct, ProductsPartialState, Product } from '@nx-example/shared/product/state'; @Component({ selector: 'nx-example-product-detail-page', template: ` @if (product | async; as product) {

{{ product.name }}

Price:

} `, styles: [ ` .product-detail { display: grid; grid-template-columns: 1fr 1fr; gap: 2rem; } `] }) export class ProductDetailPageComponent { private store = inject>(Store); private route = inject(ActivatedRoute); product: Observable = this.route.paramMap.pipe( map((paramMap) => paramMap.get('productId')), concatMap((productId) => this.store.pipe( select(getProductsState), select(getProduct, productId) ) ) ); addToCart(product: Product) { console.log(`Adding ${product.name} to cart`); } } // App routing configuration RouterModule.forRoot([ { path: 'product', loadChildren: () => import('@nx-example/products/product-detail-page').then( (module) => module.ProductsProductDetailPageModule ), } ]) ``` -------------------------------- ### Calculate Cart Item and Total Costs with TypeScript Source: https://context7.com/nrwl/nx-examples/llms.txt Calculates the cost for individual cart items and the total cost of the entire cart. It relies on functions imported from '@nx-example/shared/cart/state' and utilizes 'CartItem', 'CartState', and 'ProductsState' types. The output is formatted as a currency string. ```typescript import { getItemCost, getTotalCost } from '@nx-example/shared/cart/state'; import { CartState, CartItem } from '@nx-example/shared/cart/state'; import { ProductsState } from '@nx-example/shared/product/state'; // Calculate cost for single cart item const cartItem: CartItem = { productId: '1', quantity: 3 }; const productsState: ProductsState = { products: [ { id: '1', name: 'A Game of Thrones', price: 10000 }, // $100.00 { id: '2', name: 'A Clash of Kings', price: 10000 } ] }; const itemCost = getItemCost(cartItem, productsState); console.log(`Item cost: $${(itemCost / 100).toFixed(2)}`); // Output: Item cost: $300.00 // Calculate total cart cost const cartState: CartState = { items: [ { productId: '1', quantity: 3 }, { productId: '2', quantity: 2 } ] }; const totalCost = getTotalCost(cartState, productsState); console.log(`Total: $${(totalCost / 100).toFixed(2)}`); // Output: Total: $500.00 // React component usage function CartTotal() { const [cartState] = useReducer(cartReducer, initialState); const [productsState] = useReducer(productsReducer, productsInitialState); const total = getTotalCost(cartState, productsState); return (

Cart Total: ${(total / 100).toFixed(2)}

{cartState.items.map(item => { const itemTotal = getItemCost(item, productsState); return (
Item Total: ${(itemTotal / 100).toFixed(2)}
); })}
); } ``` -------------------------------- ### Cart State Management with NgRx and React Hooks Source: https://context7.com/nrwl/nx-examples/llms.txt Manages cart state using a Redux pattern. Supports both Angular with NgRx and React with hooks. It defines cart state, items, and actions for updating quantities. Dependencies include '@nx-example/shared/cart/state' for state logic and '@ngrx/store' for Angular. ```typescript // Define cart state and actions import { CartActionTypes, SetQuantity } from '@nx-example/shared/cart/state'; import { cartReducer, initialState } from '@nx-example/shared/cart/state'; // Cart state structure interface CartState { items: CartItem[]; } interface CartItem { productId: string; quantity: number; } // React usage with useReducer import { useReducer } from 'react'; function CartComponent() { const [cartState, dispatch] = useReducer(cartReducer, initialState); // Update quantity const handleQuantityChange = (productId: string, quantity: number) => { dispatch(new SetQuantity(productId, quantity)); }; return (
{cartState.items.map(item => (
Product: {item.productId}, Quantity: {item.quantity}
))}
); } // Angular NgRx usage import { Store } from '@ngrx/store'; import { SetQuantity } from '@nx-example/shared/cart/state'; import { Component, inject } from '@angular/core'; @Component({ selector: 'app-cart', template: `
Product: {{item.productId}}, Quantity: {{item.quantity}}
` }) export class CartComponent { private store = inject(Store); cartItems$ = this.store.select(state => state.cart.items); updateQuantity(productId: string, quantity: number) { this.store.dispatch(new SetQuantity(productId, quantity)); } } ``` -------------------------------- ### React Shopping Cart Page Component with State Management (TypeScript) Source: https://context7.com/nrwl/nx-examples/llms.txt Implements a complete shopping cart page using React and TypeScript. It utilizes the `useReducer` hook for managing both product and cart states, integrating with shared state modules for cart and product data. Includes functions for calculating item and total costs. ```typescript import { useReducer } from 'react'; import { cartReducer, initialState as cartInitialState } from '@nx-example/shared/cart/state/react'; import { productsReducer, initialState as productsInitialState } from '@nx-example/shared/product/state/react'; import { SetQuantity } from '@nx-example/shared/cart/state/react'; import { getItemCost, getTotalCost } from '@nx-example/shared/cart/state/react'; import '@nx-example/shared/product/ui'; export const CartCartPage = () => { const [productsState] = useReducer(productsReducer, productsInitialState); const { products } = productsState; const [cartState, dispatch] = useReducer(cartReducer, { items: products.map((product) => ({ productId: product.id, quantity: 1, })), }); const handleQuantityChange = (productId: string, quantity: number) => { dispatch(new SetQuantity(productId, quantity)); }; const totalCost = getTotalCost(cartState, productsState); return (

Shopping Cart

    {cartState.items.map((item) => { const product = products.find((p) => p.id === item.productId); if (!product) return null; const itemTotal = getItemCost(item, productsState); return (
  • {product.name}

    {product.name}

    Price:

    Item Total: ${(itemTotal / 100).toFixed(2)}

  • ); })}

Total: ${(totalCost / 100).toFixed(2)}

); }; ``` -------------------------------- ### Angular Product List Page: Module and Component Source: https://context7.com/nrwl/nx-examples/llms.txt Defines the Angular module and component for the product list page. It utilizes NgRx for state management to fetch and display products. The module is designed for lazy loading, and the component uses Angular's async pipe to handle observable data streams for the product list. ```typescript // Module definition import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule } from '@angular/router'; import { SharedProductStateModule } from '@nx-example/shared/product/state'; import '@nx-example/shared/product/ui'; @NgModule({ imports: [ CommonModule, SharedProductStateModule, RouterModule.forChild([ { path: '', pathMatch: 'full', component: HomePageComponent }, ]), ], declarations: [HomePageComponent], schemas: [CUSTOM_ELEMENTS_SCHEMA], }) export class ProductsHomePageModule {} // Component implementation import { Component, inject } from '@angular/core'; import { Store, select } from '@ngrx/store'; import { Observable } from 'rxjs'; import { getProductsState, getProducts, ProductsPartialState, Product } from '@nx-example/shared/product/state'; @Component({ selector: 'products-home-page', template: `

Product Catalog

`, styles: [ ` .product-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 2rem; } `] }) export class HomePageComponent { private store = inject>(Store); products: Observable = this.store.pipe( select(getProductsState), select(getProducts) ); } // Lazy load in app routing RouterModule.forRoot([ { path: '', pathMatch: 'full', loadChildren: () => import('@nx-example/products/home-page').then( (module) => module.ProductsHomePageModule ), } ]) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.