### Bootstrap Application with runApp Source: https://github.com/angulardart-community/angular/blob/master/ngdart/CHANGELOG.md The recommended way to start an AngularDart application using a generated ComponentFactory. ```dart import 'package:angular/angular.dart'; import 'main.template.dart' as ng; void main() { runApp(ng.RootComponentNgFactory); } @Component( selector: 'root', template: 'Hello World', ) class RootComponent {} ``` -------------------------------- ### Async Bootstrap with runAppAsync Source: https://context7.com/angulardart-community/angular/llms.txt An asynchronous alternative to `runApp` that allows for initialization logic before the main component is created. Use the `beforeComponentCreated` callback for asynchronous setup. ```dart import 'package:ngdart/angular.dart'; import 'main.template.dart' as ng; void main() { runAppAsync( ng.AppComponentNgFactory, beforeComponentCreated: (Injector injector) async { final configService = injector.provideType(ConfigService); await configService.loadConfiguration(); }, createInjector: appInjector, ); } ``` -------------------------------- ### Component Initialization and Cleanup with OnInit and OnDestroy Source: https://context7.com/angulardart-community/angular/llms.txt Implement OnInit for initialization logic after the first change detection and OnDestroy for cleanup before the component is destroyed. This example sets up and cancels a stream subscription. ```dart import 'dart:async'; import 'package:ngdart/angular.dart'; @Component( selector: 'user-panel', template: 'Online users: {{count}}', ) class UserPanelComponent implements OnInit, OnDestroy { StreamSubscription? _onlineUserSub; int count = 0; @override void ngOnInit() { // Called after first change detection _onlineUserSub = onlineUsers.listen((count) => this.count = count); } @override void ngOnDestroy() { // Called before component is destroyed _onlineUserSub?.cancel(); } } ``` -------------------------------- ### Core Framework - runApp Source: https://context7.com/angulardart-community/angular/llms.txt Starts a new AngularDart application with a component factory as the root. This is the primary method for bootstrapping an AngularDart application. ```APIDOC ## Core Framework - runApp ### Description Starts a new AngularDart application with a component factory as the root. Creates an injector with change detection and other framework internals. ### Method `runApp` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart // main.dart import 'package:ngdart/angular.dart'; import 'main.template.dart' as ng; @Component( selector: 'hello-world', template: 'Hello World', ) class HelloWorldComponent {} void main() { runApp(ng.HelloWorldComponentNgFactory); } ``` ### Response None (application starts) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Build AngularDart Binary Source: https://github.com/angulardart-community/angular/blob/master/examples/hello_world/README.md This command builds a production-ready binary for your AngularDart application. Always run 'pub get' before building. ```bash $ pub get $ webdev build ``` -------------------------------- ### Bootstrap Application with runApp Source: https://context7.com/angulardart-community/angular/llms.txt Starts a new AngularDart application with a component factory as the root. Requires importing the 'angular.dart' package and the component's template. ```dart // main.dart import 'package:ngdart/angular.dart'; import 'main.template.dart' as ng; @Component( selector: 'hello-world', template: 'Hello World', ) class HelloWorldComponent {} void main() { runApp(ng.HelloWorldComponentNgFactory); } ``` -------------------------------- ### Type-Safe Injector API Usage Source: https://github.com/angulardart-community/angular/blob/master/ngdart/CHANGELOG.md Demonstrates the new type-safe `provide` and `provideToken` methods for injecting dependencies via the `Injector` API, replacing older dynamic `get` calls. ```dart void example(Injector injector) { // Injecting "SomeType". // Before: var someType1 = injector.get(SomeType) as SomeType; // After: var someType2 = injector.provide(); // Injecting "OpaqueToken(...)". // Before: var someToken1 = injector.get(someToken) as SomeType; // After: var someToken2 = injector.provideToken(someToken); } ``` -------------------------------- ### Host Element Interaction with @HostBinding and @HostListener Source: https://context7.com/angulardart-community/angular/llms.txt Use @HostBinding to bind to host element properties and @HostListener to listen to host element events. This example demonstrates toggling a class and responding to click and mouseenter events. ```dart import 'package:ngdart/angular.dart'; import 'package:web/web.dart'; @Component( selector: 'button-like', template: 'CLICK ME', ) class ButtonLikeComponent { @HostBinding('attr.role') final String role = 'button'; @HostBinding('class.active') bool isActive = false; @HostListener('click') void onClick(MouseEvent event) { isActive = !isActive; print('Button clicked!'); } @HostListener('mouseenter') void onMouseEnter() { print('Mouse entered'); } } ``` -------------------------------- ### Serve AngularDart Locally with Dart2JS (Minified) Source: https://github.com/angulardart-community/angular/blob/master/examples/hello_world/README.md Use this command to serve your AngularDart application locally with Dart2JS, applying minification for a release build. Run 'pub get' before serving. ```bash $ pub get $ webdev serve --release ``` -------------------------------- ### Deferred component inside template Source: https://github.com/angulardart-community/angular/blob/master/ngdart/CHANGELOG.md Example of a deferred component used as a direct child of a template tag. ```html ``` -------------------------------- ### Serve AngularDart Locally with DDC Source: https://github.com/angulardart-community/angular/blob/master/examples/hello_world/README.md Use this command to serve your AngularDart application locally for debugging with the Dart Development Compiler (DDC). Ensure you have run 'pub get' first. ```bash $ pub get $ webdev serve ``` -------------------------------- ### Reacting to Input Changes with AfterChanges Source: https://context7.com/angulardart-community/angular/llms.txt The AfterChanges lifecycle hook is called when any data-bound @Input properties change, before view and content children are checked. This example updates a display text based on an input status. ```dart import 'package:ngdart/angular.dart'; @Component( selector: 'status-display', template: '{{displayText}}', ) class StatusDisplayComponent implements AfterChanges { @Input() String status = ''; String displayText = ''; @override void ngAfterChanges() { // Called when @Input properties change displayText = 'Current status: $status'; } } ``` -------------------------------- ### Querying View Elements with @ViewChild and @ViewChildren Source: https://context7.com/angulardart-community/angular/llms.txt Use @ViewChild and @ViewChildren to query for child components or elements within a component's template. This example shows how to access a single child and a list of children after the view is initialized. ```dart import 'package:ngdart/angular.dart'; @Component( selector: 'child-cmp', template: '

child

', ) class ChildComponent { void doSomething() => print('Doing something'); } @Component( selector: 'parent', template: ''' ''', directives: [ChildComponent], ) class ParentComponent implements AfterViewInit { @ViewChild(ChildComponent) ChildComponent? firstChild; @ViewChildren(ChildComponent) List? allChildren; @override void ngAfterViewInit() { firstChild?.doSomething(); for (var child in allChildren ?? []) { child.doSomething(); } } } ``` -------------------------------- ### Bootstrap Legacy Applications Source: https://github.com/angulardart-community/angular/blob/master/ngdart/CHANGELOG.md Use runAppLegacy for migration purposes when reflective metadata is still required. ```dart import 'package:angular/angular.dart'; // ignore: uri_has_not_been_generated import 'main.template.dart' as ng; void main() { runAppLegacy( RootComponent, createInjectorFromProviders: [ ClassProvider(HelloService), ], initReflector: ng.initReflector, ); } ``` -------------------------------- ### Define Module Configuration Source: https://github.com/angulardart-community/angular/blob/master/ngdart/CHANGELOG.md Demonstrates the legacy list-based provider configuration and the modern typed Module syntax for dependency injection. ```dart const commonModule = [ httpModule, ClassProvider(AuthService, useClass: OAuthService), FactoryProvider.forToken(xsrfToken, useFactory: readXsrfToken), ]; ``` ```dart const httpModule = Module( /* ... Configuration ... */); const commonModule = Module( include: [httpModule], provide: [ ClassProvider(AuthService, useClass: OAuthService), FactoryProvider.forToken(xsrfToken, useFactory: readXsrfToken), ], ); ``` -------------------------------- ### Core Framework - runAppAsync Source: https://context7.com/angulardart-community/angular/llms.txt An asynchronous alternative to `runApp` that supports initialization logic before the main component is created. ```APIDOC ## Core Framework - runAppAsync ### Description Asynchronous alternative to `runApp` that supports initialization before component creation. ### Method `runAppAsync` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart import 'package:ngdart/angular.dart'; import 'main.template.dart' as ng; void main() { runAppAsync( ng.AppComponentNgFactory, beforeComponentCreated: (Injector injector) async { final configService = injector.provideType(ConfigService); await configService.loadConfiguration(); }, createInjector: appInjector, ); } ``` ### Response None (application starts) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Set up prerequisite data using Injector before component creation Source: https://github.com/angulardart-community/angular/blob/master/ngtest/CHANGELOG.md Demonstrates using the Injector within `beforeComponentCreated` to set up prerequisite data for testing from Dependency Injection before a component is loaded. ```dart final fixture = await testBed.create( beforeComponentCreated: (i) { var dataLayer = i.get(ComplexDataLayer) as ComplexDataLayer; dataLayer.setUpMockDataForTesting(); }, ); ``` -------------------------------- ### Bootstrap with InjectorFactory Source: https://github.com/angulardart-community/angular/blob/master/ngdart/CHANGELOG.md Configuring top-level services during application bootstrap using a generated InjectorFactory. ```dart import 'package:angular/angular.dart'; import 'main.template.dart' as ng; void main() { runApp(ng.RootComponentNgFactory, createInjector: rootInjector); } class HelloService { void sayHello() => print('Hello!'); } @GenerateInjector([ ClassProvider(HelloService), ]) final InjectorFactory rootInjector = ng.rootInjector$Injector; ``` -------------------------------- ### Core Framework - runApp with Dependency Injection Source: https://context7.com/angulardart-community/angular/llms.txt Bootstraps an AngularDart application with custom providers using `@GenerateInjector` for compile-time dependency injection. ```APIDOC ## Core Framework - runApp with Dependency Injection ### Description Bootstraps application with custom providers using `@GenerateInjector` for compile-time dependency injection. ### Method `runApp` with `createInjector` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart import 'package:ngdart/angular.dart'; import 'main.template.dart' as ng; class HelloService { void sayHello() => print('Hello World!'); } @Component( selector: 'hello-world', template: '', ) class HelloWorldComponent { HelloWorldComponent(HelloService service) { service.sayHello(); } } @GenerateInjector([ ClassProvider(HelloService), ]) final InjectorFactory helloInjector = ng.helloInjector$Injector; void main() { runApp(ng.HelloWorldComponentNgFactory, createInjector: helloInjector); } ``` ### Response None (application starts) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Querying Projected Content with @ContentChild and @ContentChildren Source: https://context7.com/angulardart-community/angular/llms.txt Use @ContentChild and @ContentChildren to query for child components projected via the tag. This example demonstrates finding TabComponents projected into a TabPanelComponent. ```dart import 'package:ngdart/angular.dart'; @Component(selector: 'tab-comp', template: 'I am a Tab!') class TabComponent {} @Component( selector: 'tab-panel', template: '', ) class TabPanelComponent implements AfterContentInit { @ContentChildren(TabComponent) List? tabs; @override void ngAfterContentInit() { print('Found ${tabs?.length ?? 0} tabs'); } } // Usage: // // // // ``` -------------------------------- ### Configure NgTestBed with Mock Services Source: https://context7.com/angulardart-community/angular/llms.txt Set up NgTestBed with mock services and custom providers for dependency injection in tests. This is useful for isolating components and controlling their dependencies. ```dart import 'package:ngdart/angular.dart'; import 'package:ngtest/ngtest.dart'; import 'package:test/test.dart'; import 'package:mockito/mockito.dart'; import 'user_profile.template.dart' as ng; abstract class UserService { Future getUser(int id); } class MockUserService extends Mock implements UserService {} @Component( selector: 'user-profile', template: '''

{{user.name}}

{{user.email}}

Loading...
''', ) class UserProfileComponent implements OnInit { final UserService _userService; User? user; bool loading = true; UserProfileComponent(this._userService); @override void ngOnInit() async { user = await _userService.getUser(1); loading = false; } } void main() { group('UserProfileComponent', () { late MockUserService mockUserService; late NgTestBed testBed; setUp(() { mockUserService = MockUserService(); testBed = NgTestBed( ng.UserProfileComponentNgFactory, rootInjector: (parent) => Injector.map({ UserService: mockUserService, }, parent), ); }); tearDown(disposeAnyRunningTest); test('should display user data', () async { // Setup mock when(mockUserService.getUser(1)).thenAnswer( (_) async => User(name: 'John', email: 'john@example.com'), ); // Create fixture (triggers ngOnInit) final fixture = await testBed.create(); // Wait for async operations await fixture.update(); expect(fixture.text, contains('John')); expect(fixture.text, contains('john@example.com')); verify(mockUserService.getUser(1)).called(1); }); test('should show loading state initially', () async { // Delay response when(mockUserService.getUser(1)).thenAnswer( (_) => Future.delayed(Duration(seconds: 1), () => User(name: 'John', email: 'john@example.com')), ); final fixture = await testBed.create(); // Check loading state before async completes expect(fixture.text, contains('Loading...')); }); }); } class User { final String name; final String email; User({required this.name, required this.email}); } ``` -------------------------------- ### Running Tests with build_runner Source: https://github.com/angulardart-community/angular/blob/master/ngtest/README.md Command to execute tests using Chrome and Dartdevc. ```bash pub run build_runner test -- -p chrome ``` -------------------------------- ### Configure Provider with single argument Source: https://github.com/angulardart-community/angular/blob/master/ngdart/CHANGELOG.md Use the Provider constructor or provide function with a single argument to provide an instance of the class. ```dart const Provider(Foo) // or provide(Foo) ``` -------------------------------- ### Encapsulating providers with Module Source: https://github.com/angulardart-community/angular/blob/master/ngdart/CHANGELOG.md Use Module to group collections of providers for cleaner configuration. ```dart const httpModule = [ /* Other providers and/or modules. */ ]; ``` -------------------------------- ### Use Module in ReflectiveInjector Source: https://github.com/angulardart-community/angular/blob/master/ngdart/CHANGELOG.md Shows how to use a Module with ReflectiveInjector. Note that this approach is discouraged for new code due to performance impacts. ```dart // Using ReflectiveInjector is strongly not recommended for new code // due to adverse effects on code-size and runtime performance. final injector = ReflectiveInjector.resolveAndCreate([ commonModule, ]); ``` -------------------------------- ### Displaying list length and item iteration Source: https://github.com/angulardart-community/angular/blob/master/ngast/test/ast_cli_tester_source.html Use interpolation to show collection size and iterate over items using the asterisk syntax. ```html Showing {{items.length}} items: =============================== * {{x}} : {{item.trim()}} ``` -------------------------------- ### Handle Event Bindings in Templates Source: https://github.com/angulardart-community/angular/blob/master/ngdart/CHANGELOG.md Event bindings now support only single statements. Use method binding for complex logic. ```html ``` ```html ``` -------------------------------- ### Configure FakeTimeNgZoneStabilizer with custom maxIterations Source: https://github.com/angulardart-community/angular/blob/master/ngtest/CHANGELOG.md Allows configuring a higher threshold for FakeTimeNgZoneStabilizer to elapse pending timers, useful in advanced test cases. ```dart NgZoneStabilizer allow100InsteadOf10() { return FakeTimeNgZoneStabilizer(timerZone, ngZone, maxIterations: 100); } ``` -------------------------------- ### Bootstrap Application with Dependency Injection Source: https://context7.com/angulardart-community/angular/llms.txt Bootstraps an AngularDart application with custom providers using `@GenerateInjector` for compile-time dependency injection. Ensure the service is provided in the injector factory. ```dart import 'package:ngdart/angular.dart'; import 'main.template.dart' as ng; class HelloService { void sayHello() => print('Hello World!'); } @Component( selector: 'hello-world', template: '', ) class HelloWorldComponent { HelloWorldComponent(HelloService service) { service.sayHello(); } } @GenerateInjector([ ClassProvider(HelloService), ]) final InjectorFactory helloInjector = ng.helloInjector$Injector; void main() { runApp(ng.HelloWorldComponentNgFactory, createInjector: helloInjector); } ``` -------------------------------- ### Apply Form Validation with Validators Source: https://context7.com/angulardart-community/angular/llms.txt Demonstrates built-in validator usage, validator composition, and the creation of custom validation functions. Includes a helper for checking control errors. ```dart import 'package:ngforms/ngforms.dart'; // Using built-in validators final requiredControl = Control('', Validators.required); final minLengthControl = Control('', Validators.minLength(3)); final maxLengthControl = Control('', Validators.maxLength(50)); final patternControl = Control('', Validators.pattern(r'^\d{5}$')); // Composing multiple validators final emailControl = Control('', Validators.compose([ Validators.required, Validators.pattern(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$'), ])); // Custom validator function Map? passwordStrengthValidator(AbstractControl control) { final value = control.value as String? ?? ''; if (value.isEmpty) return null; final hasUppercase = value.contains(RegExp(r'[A-Z]')); final hasLowercase = value.contains(RegExp(r'[a-z]')); final hasDigit = value.contains(RegExp(r'[0-9]')); final hasSpecial = value.contains(RegExp(r'[!@#$%^&*]')); if (!hasUppercase || !hasLowercase || !hasDigit || !hasSpecial) { return { 'passwordStrength': { 'hasUppercase': hasUppercase, 'hasLowercase': hasLowercase, 'hasDigit': hasDigit, 'hasSpecial': hasSpecial, } }; } return null; } final passwordControl = Control('', Validators.compose([ Validators.required, Validators.minLength(8), passwordStrengthValidator, ])); // Check validation errors void checkErrors(Control control) { if (control.hasError('required')) { print('Field is required'); } if (control.hasError('minlength')) { final error = control.getError('minlength'); print('Minimum length: ${error['requiredLength']}, actual: ${error['actualLength']}'); } } ``` -------------------------------- ### Configure angular_test arguments Source: https://github.com/angulardart-community/angular/blob/master/ngtest/CHANGELOG.md Pass arguments to the underlying test or serve processes using the --serve-arg and --test-arg flags. ```bash $ pub run angular_test --serve-arg=port=1234 ``` ```bash $ pub run angular_test --test-arg=--tags=aot ``` ```bash $ pub run angular_test --test-arg=--platform=content-shell ``` ```bash $ pub run angular_test --serve-arg=web-compiler=dartdevc ``` -------------------------------- ### Template Attribute Syntax Replacement Source: https://github.com/angulardart-community/angular/blob/master/ngdart/CHANGELOG.md Shows the transition from the legacy 'template' attribute syntax to modern alternatives. The 'template' attribute is removed and should be replaced by either the '*' micro-syntax or a '