code
stringlengths
2.5k
150k
kind
stringclasses
1 value
angular @angular/animations @angular/animations =================== `package` Implements a domain-specific language (DSL) for defining web animation sequences for HTML elements as multiple transformations over time. Use this API to define how an HTML element can move, change color, grow or shrink, fade, or slide off the page. These changes can occur simultaneously or sequentially. You can control the timing of each of these transformations. The function calls generate the data structures and metadata that enable Angular to integrate animations into templates and run them based on application states. Animation definitions are linked to components through the `[animations](core/component#animations)` property in the `@[Component](core/component)` metadata, typically in the component file of the HTML element to be animated. The `[trigger](animations/trigger)()` function encapsulates a named animation, with all other function calls nested within. Use the trigger name to bind the named animation to a specific triggering element in the HTML template. Angular animations are based on CSS web transition functionality, so anything that can be styled or transformed in CSS can be animated the same way in Angular. Angular animations allow you to: * Set animation timings, styles, keyframes, and transitions. * Animate HTML elements in complex sequences and choreographies. * Animate HTML elements as they are inserted and removed from the DOM, including responsive real-time filtering. * Create reusable animations. * Animate parent and child elements. Additional animation functionality is provided in other Angular modules for animation testing, for route-based animations, and for programmatic animation controls that allow an end user to fast forward and reverse an animation sequence. See also -------- * Find out more in the [animations guide](../guide/animations). * See what polyfills you might need in the [browser support guide](../guide/browser-support). Entry points ------------ ### Primary | | | | --- | --- | | `[@angular/animations](animations#primary-entry-point-exports)` | Implements a domain-specific language (DSL) for defining web animation sequences for HTML elements as multiple transformations over time. | ### Secondary | | | | --- | --- | | `[@angular/animations/browser](animations/browser)` | Provides infrastructure for cross-platform rendering of animations in a browser. | | `[@angular/animations/browser/testing](animations/browser/testing)` | Provides infrastructure for testing of the Animations browser subsystem. | Primary entry point exports --------------------------- ### Classes | | | | --- | --- | | `[AnimationBuilder](animations/animationbuilder)` | An injectable service that produces an animation sequence programmatically within an Angular component or directive. Provided by the `[BrowserAnimationsModule](platform-browser/animations/browseranimationsmodule)` or `[NoopAnimationsModule](platform-browser/animations/noopanimationsmodule)`. | | `[AnimationFactory](animations/animationfactory)` | A factory object returned from the `[AnimationBuilder.build](animations/animationbuilder#build)()` method. | | `[NoopAnimationPlayer](animations/noopanimationplayer)` | An empty programmatic controller for reusable animations. Used internally when animations are disabled, to avoid checking for the null case when an animation player is expected. | ### Functions | | | | --- | --- | | `[animate](animations/animate)` | Defines an animation step that combines styling information with timing information. | | `[animateChild](animations/animatechild)` | Executes a queried inner animation element within an animation sequence. | | `[animation](animations/animation)` | Produces a reusable animation that can be invoked in another animation or sequence, by calling the `[useAnimation](animations/useanimation)()` function. | | `[group](animations/group)` | Defines a list of animation steps to be run in parallel. | | `[keyframes](animations/keyframes)` | Defines a set of animation styles, associating each style with an optional `offset` value. | | `[query](animations/query)` | Finds one or more inner elements within the current element that is being animated within a sequence. Use with `[animate](animations/animate)()`. | | `[sequence](animations/sequence)` | Defines a list of animation steps to be run sequentially, one by one. | | `[stagger](animations/stagger)` | Use within an animation `[query](animations/query)()` call to issue a timing gap after each queried item is animated. | | `[state](animations/state)` | Declares an animation state within a trigger attached to an element. | | `[style](animations/style)` | Declares a key/value object containing CSS properties/styles that can then be used for an animation [`state`](animations/state), within an animation `[sequence](animations/sequence)`, or as styling data for calls to `[animate](animations/animate)()` and `[keyframes](animations/keyframes)()`. | | `[transition](animations/transition)` | Declares an animation transition which is played when a certain specified condition is met. | | `[trigger](animations/trigger)` | Creates a named animation trigger, containing a list of [`state()`](animations/state) and `[transition](animations/transition)()` entries to be evaluated when the expression bound to the trigger changes. | | `[useAnimation](animations/useanimation)` | Starts a reusable animation that is created using the `[animation](animations/animation)()` function. | ### Structures | | | | --- | --- | | `[AnimateChildOptions](animations/animatechildoptions)` | Adds duration options to control animation styling and timing for a child animation. | | `[AnimationAnimateChildMetadata](animations/animationanimatechildmetadata)` | Encapsulates a child animation, that can be run explicitly when the parent is run. Instantiated and returned by the `[animateChild](animations/animatechild)` function. | | `[AnimationAnimateMetadata](animations/animationanimatemetadata)` | Encapsulates an animation step. Instantiated and returned by the `[animate](animations/animate)()` function. | | `[AnimationAnimateRefMetadata](animations/animationanimaterefmetadata)` | Encapsulates a reusable animation. Instantiated and returned by the `[useAnimation](animations/useanimation)()` function. | | `[AnimationEvent](animations/animationevent)` | An instance of this class is returned as an event parameter when an animation callback is captured for an animation either during the start or done phase. | | `[AnimationGroupMetadata](animations/animationgroupmetadata)` | Encapsulates an animation group. Instantiated and returned by the `[group()](animations/group)` function. | | `[AnimationKeyframesSequenceMetadata](animations/animationkeyframessequencemetadata)` | Encapsulates a keyframes sequence. Instantiated and returned by the `[keyframes](animations/keyframes)()` function. | | `[AnimationMetadata](animations/animationmetadata)` | Base for animation data structures. | | `[AnimationMetadataType](animations/animationmetadatatype)` | Constants for the categories of parameters that can be defined for animations. | | `[AnimationOptions](animations/animationoptions)` | Options that control animation styling and timing. | | `[AnimationPlayer](animations/animationplayer)` | Provides programmatic control of a reusable animation sequence, built using the `[AnimationBuilder.build](animations/animationbuilder#build)()` method which returns an `[AnimationFactory](animations/animationfactory)`, whose `[create](animations/animationfactory#create)()` method instantiates and initializes this interface. | | `[AnimationQueryMetadata](animations/animationquerymetadata)` | Encapsulates an animation query. Instantiated and returned by the `[query](animations/query)()` function. | | `[AnimationQueryOptions](animations/animationqueryoptions)` | Encapsulates animation query options. Passed to the `[query](animations/query)()` function. | | `[AnimationReferenceMetadata](animations/animationreferencemetadata)` | Encapsulates a reusable animation, which is a collection of individual animation steps. Instantiated and returned by the `[animation](animations/animation)()` function, and passed to the `[useAnimation](animations/useanimation)()` function. | | `[AnimationSequenceMetadata](animations/animationsequencemetadata)` | Encapsulates an animation sequence. Instantiated and returned by the `[sequence](animations/sequence)()` function. | | `[AnimationStaggerMetadata](animations/animationstaggermetadata)` | Encapsulates parameters for staggering the start times of a set of animation steps. Instantiated and returned by the `[stagger](animations/stagger)()` function. | | `[AnimationStateMetadata](animations/animationstatemetadata)` | Encapsulates an animation state by associating a state name with a set of CSS styles. Instantiated and returned by the [`state()`](animations/state) function. | | `[AnimationStyleMetadata](animations/animationstylemetadata)` | Encapsulates an animation style. Instantiated and returned by the `[style](animations/style)()` function. | | `[AnimationTransitionMetadata](animations/animationtransitionmetadata)` | Encapsulates an animation transition. Instantiated and returned by the `[transition](animations/transition)()` function. | | `[AnimationTriggerMetadata](animations/animationtriggermetadata)` | Contains an animation trigger. Instantiated and returned by the `[trigger](animations/trigger)()` function. | ### Types | | | | --- | --- | | `[AUTO\_STYLE](animations/auto_style)` | Specifies automatic styling. | | `[AnimateTimings](animations/animatetimings)` | Represents animation-step timing parameters for an animation step. | angular @angular/platform-browser-dynamic @angular/platform-browser-dynamic ================================= `package` Supports [JIT](../guide/glossary#jit) compilation and execution of Angular apps on different supported browsers. Entry points ------------ ### Primary | | | | --- | --- | | `[@angular/platform-browser-dynamic](platform-browser-dynamic#primary-entry-point-exports)` | Supports [JIT](../guide/glossary#jit) compilation and execution of Angular apps on different supported browsers. | ### Secondary | | | | --- | --- | | `[@angular/platform-browser-dynamic/testing](platform-browser-dynamic/testing)` | Supplies a testing module for the Angular JIT platform-browser subsystem. | Primary entry point exports --------------------------- ### Classes | | | | --- | --- | | `[JitCompilerFactory](platform-browser-dynamic/jitcompilerfactory)` | **Deprecated:** Ivy JIT mode doesn't require accessing this symbol. See [JIT API changes due to ViewEngine deprecation](../guide/deprecations#jit-api-changes) for additional context. | ### Types | | | | --- | --- | | `[RESOURCE\_CACHE\_PROVIDER](platform-browser-dynamic/resource_cache_provider)` | **Deprecated:** This was previously necessary in some cases to test AOT-compiled components with View Engine, but is no longer since Ivy. | | `[platformBrowserDynamic](platform-browser-dynamic/platformbrowserdynamic)` | | angular @angular/localize @angular/localize ================= `package` The `@angular/localize` package contains helpers and tools for localizing your application. You should install this package using `ng add @angular/localize` if you need to tag text in your application that you want to be translatable. The approach is based around the concept of tagging strings in code with a [template literal tag handler](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates) called `[$localize](localize/init/%24localize)`. The idea is that strings that need to be translated are “marked” using this tag: ``` const message = $localize`Hello, World!`; ``` This `[$localize](localize/init/%24localize)` identifier can be a real function that can do the translation at runtime, in the browser. But, significantly, it is also a global identifier that survives minification. This means it can act simply as a marker in the code that a static post-processing tool can use to replace the original text with translated text before the code is deployed. For example, the following code: ``` warning = $localize`${this.process} is not right`; ``` could be replaced with: ``` warning = "" + this.process + ", ce n'est pas bon."; ``` The result is that all references to `[$localize](localize/init/%24localize)` are removed, and there is **zero runtime cost** to rendering the translated text. The Angular template compiler also generates `[$localize](localize/init/%24localize)` tagged strings rather than doing the translation itself. For example, the following template: ``` <h1 i18n>Hello, World!</h1> ``` would be compiled to something like: ``` ɵɵelementStart(0, "h1"); // <h1> ɵɵi18n(1, $localize`Hello, World!`); // Hello, World! ɵɵelementEnd(); // </h1> ``` This means that after the Angular compiler has completed its work, all the template text marked with `i18n` attributes have been converted to `[$localize](localize/init/%24localize)` tagged strings, which can be processed just like any other tagged string. Entry points ------------ ### Primary | | | | --- | --- | | `[@angular/localize](localize#primary-entry-point-exports)` | The `@angular/localize` package contains helpers and tools for localizing your application. | ### Secondary | | | | --- | --- | | `[@angular/localize/init](localize/init)` | The `@angular/localize` package exposes the `[$localize](localize/init/%24localize)` function in the global namespace, which can be used to tag i18n messages in your code that needs to be translated. | Primary entry point exports --------------------------- ### Functions | | | | --- | --- | | `[clearTranslations](localize/cleartranslations)` | Remove all translations for `[$localize](localize/init/%24localize)`, if doing runtime translation. | | `[loadTranslations](localize/loadtranslations)` | Load translations for use by `[$localize](localize/init/%24localize)`, if doing runtime translation. | ### Types | | | | --- | --- | | `[MessageId](localize/messageid)` | A string that uniquely identifies a message, to be used for matching translations. | | `[TargetMessage](localize/targetmessage)` | A string containing a translation target message. | angular UpgradeAdapterRef UpgradeAdapterRef ================= `class` `deprecated` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Use `[UpgradeAdapterRef](upgradeadapterref)` to control a hybrid AngularJS / Angular application. **Deprecated:** Deprecated since v5. Use `[upgrade/static](static)` instead, which also supports [Ahead-of-Time compilation](../../guide/aot-compiler). ``` class UpgradeAdapterRef { ng1RootScope: IRootScopeService ng1Injector: IInjectorService ng2ModuleRef: NgModuleRef<any> ng2Injector: Injector ready(fn: (upgradeAdapterRef: UpgradeAdapterRef) => void) dispose() } ``` Properties ---------- | Property | Description | | --- | --- | | `ng1RootScope: IRootScopeService` | | | `ng1Injector: IInjectorService` | | | `ng2ModuleRef: [NgModuleRef](../core/ngmoduleref)<any>` | | | `ng2Injector: [Injector](../core/injector)` | | Methods ------- | ready() | | --- | | Register a callback function which is notified upon successful hybrid AngularJS / Angular application has been bootstrapped. | | `ready(fn: (upgradeAdapterRef: UpgradeAdapterRef) => void)` Parameters | | | | | --- | --- | --- | | `fn` | `(upgradeAdapterRef: [UpgradeAdapterRef](upgradeadapterref)) => void` | | | | The `ready` callback function is invoked inside the Angular zone, therefore it does not require a call to `$apply()`. | | dispose() | | --- | | Dispose of running hybrid AngularJS / Angular application. | | `dispose()` Parameters There are no parameters. | angular UpgradeAdapter UpgradeAdapter ============== `class` `deprecated` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Use `[UpgradeAdapter](upgradeadapter)` to allow AngularJS and Angular to coexist in a single application. [See more...](upgradeadapter#description) **Deprecated:** Deprecated since v5. Use `[upgrade/static](static)` instead, which also supports [Ahead-of-Time compilation](../../guide/aot-compiler). ``` class UpgradeAdapter { constructor(ng2AppModule: Type<any>, compilerOptions?: CompilerOptions) downgradeNg2Component(component: Type<any>): Function upgradeNg1Component(name: string): Type<any> registerForNg1Tests(modules?: string[]): UpgradeAdapterRef bootstrap(element: Element, modules?: any[], config?: IAngularBootstrapConfig): UpgradeAdapterRef upgradeNg1Provider(name: string, options?: { asToken: any; }) downgradeNg2Provider(token: any): Function } ``` Description ----------- The `[UpgradeAdapter](upgradeadapter)` allows: 1. creation of Angular component from AngularJS component directive (See [UpgradeAdapter#upgradeNg1Component()]) 2. creation of AngularJS directive from Angular component. (See [UpgradeAdapter#downgradeNg2Component()]) 3. Bootstrapping of a hybrid Angular application which contains both of the frameworks coexisting in a single application. Further information is available in the [Usage Notes...](upgradeadapter#usage-notes) Constructor ----------- | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | | `constructor(ng2AppModule: Type<any>, compilerOptions?: CompilerOptions)` Parameters | | | | | --- | --- | --- | | `ng2AppModule` | `[Type](../core/type)<any>` | | | `compilerOptions` | `[CompilerOptions](../core/compileroptions)` | Optional. Default is `undefined`. | | Methods ------- | downgradeNg2Component() | | --- | | Allows Angular Component to be used from AngularJS. | | `downgradeNg2Component(component: Type<any>): Function` Parameters | | | | | --- | --- | --- | | `component` | `[Type](../core/type)<any>` | | Returns `Function` | | Use `downgradeNg2Component` to create an AngularJS Directive Definition Factory from Angular Component. The adapter will bootstrap Angular component from within the AngularJS template. | | Usage Notes Mental Model1. The component is instantiated by being listed in AngularJS template. This means that the host element is controlled by AngularJS, but the component's view will be controlled by Angular. 2. Even thought the component is instantiated in AngularJS, it will be using Angular syntax. This has to be done, this way because we must follow Angular components do not declare how the attributes should be interpreted. 3. `ng-model` is controlled by AngularJS and communicates with the downgraded Angular component by way of the `[ControlValueAccessor](../forms/controlvalueaccessor)` interface from @angular/forms. Only components that implement this interface are eligible. Supported Features* Bindings: + Attribute: `<comp name="World">` + Interpolation: `<comp greeting="Hello {{name}}!">` + Expression: `<comp [name]="username">` + Event: `<comp (close)="doSomething()">` + ng-model: `<comp ng-model="name">` * Content projection: yes Example ``` const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module)); const module = angular.module('myExample', []); module.directive('greet', adapter.downgradeNg2Component(Greeter)); @Component({ selector: 'greet', template: '{{salutation}} {{name}}! - <ng-content></ng-content>' }) class Greeter { @Input() salutation: string; @Input() name: string; } @NgModule({ declarations: [Greeter], imports: [BrowserModule] }) class MyNg2Module {} document.body.innerHTML = 'ng1 template: <greet salutation="Hello" [name]="world">text</greet>'; adapter.bootstrap(document.body, ['myExample']).ready(function() { expect(document.body.textContent).toEqual("ng1 template: Hello world! - text"); }); ``` | | upgradeNg1Component() | | --- | | Allows AngularJS Component to be used from Angular. | | `upgradeNg1Component(name: string): Type<any>` Parameters | | | | | --- | --- | --- | | `name` | `string` | | Returns `[Type](../core/type)<any>` | | Use `upgradeNg1Component` to create an Angular component from AngularJS Component directive. The adapter will bootstrap AngularJS component from within the Angular template. | | Usage Notes Mental Model1. The component is instantiated by being listed in Angular template. This means that the host element is controlled by Angular, but the component's view will be controlled by AngularJS. Supported Features* Bindings: + Attribute: `<comp name="World">` + Interpolation: `<comp greeting="Hello {{name}}!">` + Expression: `<comp [name]="username">` + Event: `<comp (close)="doSomething()">` * Transclusion: yes * Only some of the features of [Directive Definition Object](https://docs.angularjs.org/api/ng/service/%24compile) are supported: + `compile`: not supported because the host element is owned by Angular, which does not allow modifying DOM structure during compilation. + `controller`: supported. (NOTE: injection of `$attrs` and `$transclude` is not supported.) + `controllerAs`: supported. + `bindToController`: supported. + `link`: supported. (NOTE: only pre-link function is supported.) + `name`: supported. + `priority`: ignored. + `replace`: not supported. + `require`: supported. + `restrict`: must be set to 'E'. + `scope`: supported. + `template`: supported. + `templateUrl`: supported. + `terminal`: ignored. + `transclude`: supported. Example ``` const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module)); const module = angular.module('myExample', []); module.directive('greet', function() { return { scope: {salutation: '=', name: '=' }, template: '{{salutation}} {{name}}! - <span ng-transclude></span>' }; }); module.directive('ng2', adapter.downgradeNg2Component(Ng2Component)); @Component({ selector: 'ng2', template: 'ng2 template: <greet salutation="Hello" [name]="world">text</greet>' }) class Ng2Component { } @NgModule({ declarations: [Ng2Component, adapter.upgradeNg1Component('greet')], imports: [BrowserModule] }) class MyNg2Module {} document.body.innerHTML = '<ng2></ng2>'; adapter.bootstrap(document.body, ['myExample']).ready(function() { expect(document.body.textContent).toEqual("ng2 template: Hello world! - text"); }); ``` | | registerForNg1Tests() | | --- | | Registers the adapter's AngularJS upgrade module for unit testing in AngularJS. Use this instead of `angular.mock.module()` to load the upgrade module into the AngularJS testing injector. | | `registerForNg1Tests(modules?: string[]): UpgradeAdapterRef` Parameters | | | | | --- | --- | --- | | `modules` | `string[]` | any AngularJS modules that the upgrade module should depend upon Optional. Default is `undefined`. | Returns `[UpgradeAdapterRef](upgradeadapterref)`: an `[UpgradeAdapterRef](upgradeadapterref)`, which lets you register a `ready()` callback to run assertions once the Angular components are ready to test through AngularJS. | | Usage Notes Example ``` const upgradeAdapter = new UpgradeAdapter(MyNg2Module); // configure the adapter with upgrade/downgrade components and services upgradeAdapter.downgradeNg2Component(MyComponent); let upgradeAdapterRef: UpgradeAdapterRef; let $compile, $rootScope; // We must register the adapter before any calls to `inject()` beforeEach(() => { upgradeAdapterRef = upgradeAdapter.registerForNg1Tests(['heroApp']); }); beforeEach(inject((_$compile_, _$rootScope_) => { $compile = _$compile_; $rootScope = _$rootScope_; })); it("says hello", (done) => { upgradeAdapterRef.ready(() => { const element = $compile("<my-component></my-component>")($rootScope); $rootScope.$apply(); expect(element.html()).toContain("Hello World"); done(); }) }); ``` | | bootstrap() | | --- | | Bootstrap a hybrid AngularJS / Angular application. | | `bootstrap(element: Element, modules?: any[], config?: IAngularBootstrapConfig): UpgradeAdapterRef` Parameters | | | | | --- | --- | --- | | `element` | `Element` | | | `modules` | `any[]` | Optional. Default is `undefined`. | | `config` | `IAngularBootstrapConfig` | Optional. Default is `undefined`. | Returns `[UpgradeAdapterRef](upgradeadapterref)` | | This `bootstrap` method is a direct replacement (takes same arguments) for AngularJS [`bootstrap`](https://docs.angularjs.org/api/ng/function/angular.bootstrap) method. Unlike AngularJS, this bootstrap is asynchronous. | | Usage Notes Example ``` const adapter = new UpgradeAdapter(MyNg2Module); const module = angular.module('myExample', []); module.directive('ng2', adapter.downgradeNg2Component(Ng2)); module.directive('ng1', function() { return { scope: { title: '=' }, template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)' }; }); @Component({ selector: 'ng2', inputs: ['name'], template: 'ng2[<ng1 [title]="name">transclude</ng1>](<ng-content></ng-content>)' }) class Ng2 { } @NgModule({ declarations: [Ng2, adapter.upgradeNg1Component('ng1')], imports: [BrowserModule] }) class MyNg2Module {} document.body.innerHTML = '<ng2 name="World">project</ng2>'; adapter.bootstrap(document.body, ['myExample']).ready(function() { expect(document.body.textContent).toEqual( "ng2[ng1[Hello World!](transclude)](project)"); }); ``` | | upgradeNg1Provider() | | --- | | Allows AngularJS service to be accessible from Angular. | | `upgradeNg1Provider(name: string, options?: { asToken: any; })` Parameters | | | | | --- | --- | --- | | `name` | `string` | | | `options` | `{ asToken: any; }` | Optional. Default is `undefined`. | | | Usage Notes Example ``` class Login { ... } class Server { ... } @Injectable() class Example { constructor(@Inject('server') server, login: Login) { ... } } const module = angular.module('myExample', []); module.service('server', Server); module.service('login', Login); const adapter = new UpgradeAdapter(MyNg2Module); adapter.upgradeNg1Provider('server'); adapter.upgradeNg1Provider('login', {asToken: Login}); adapter.bootstrap(document.body, ['myExample']).ready((ref) => { const example: Example = ref.ng2Injector.get(Example); }); ``` | | downgradeNg2Provider() | | --- | | Allows Angular service to be accessible from AngularJS. | | `downgradeNg2Provider(token: any): Function` Parameters | | | | | --- | --- | --- | | `token` | `any` | | Returns `Function` | | Usage Notes Example ``` class Example { } const adapter = new UpgradeAdapter(MyNg2Module); const module = angular.module('myExample', []); module.factory('example', adapter.downgradeNg2Provider(Example)); adapter.bootstrap(document.body, ['myExample']).ready((ref) => { const example: Example = ref.ng1Injector.get('example'); }); ``` | Usage notes ----------- ### Mental Model When reasoning about how a hybrid application works it is useful to have a mental model which describes what is happening and explains what is happening at the lowest level. 1. There are two independent frameworks running in a single application, each framework treats the other as a black box. 2. Each DOM element on the page is owned exactly by one framework. Whichever framework instantiated the element is the owner. Each framework only updates/interacts with its own DOM elements and ignores others. 3. AngularJS directives always execute inside AngularJS framework codebase regardless of where they are instantiated. 4. Angular components always execute inside Angular framework codebase regardless of where they are instantiated. 5. An AngularJS component can be upgraded to an Angular component. This creates an Angular directive, which bootstraps the AngularJS component directive in that location. 6. An Angular component can be downgraded to an AngularJS component directive. This creates an AngularJS directive, which bootstraps the Angular component in that location. 7. Whenever an adapter component is instantiated the host element is owned by the framework doing the instantiation. The other framework then instantiates and owns the view for that component. This implies that component bindings will always follow the semantics of the instantiation framework. The syntax is always that of Angular syntax. 8. AngularJS is always bootstrapped first and owns the bottom most view. 9. The new application is running in Angular zone, and therefore it no longer needs calls to `$apply()`. ### Example ``` const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module), myCompilerOptions); const module = angular.module('myExample', []); module.directive('ng2Comp', adapter.downgradeNg2Component(Ng2Component)); module.directive('ng1Hello', function() { return { scope: { title: '=' }, template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)' }; }); @Component({ selector: 'ng2-comp', inputs: ['name'], template: 'ng2[<ng1-hello [title]="name">transclude</ng1-hello>](<ng-content></ng-content>)', directives: }) class Ng2Component { } @NgModule({ declarations: [Ng2Component, adapter.upgradeNg1Component('ng1Hello')], imports: [BrowserModule] }) class MyNg2Module {} document.body.innerHTML = '<ng2-comp name="World">project</ng2-comp>'; adapter.bootstrap(document.body, ['myExample']).ready(function() { expect(document.body.textContent).toEqual( "ng2[ng1[Hello World!](transclude)](project)"); }); ```
programming_docs
angular @angular/upgrade/static @angular/upgrade/static ======================= `entry-point` Supports the upgrade path from AngularJS to Angular, allowing components and services from both systems to be used in the same application. Entry point exports ------------------- ### NgModules | | | | --- | --- | | `[UpgradeModule](static/upgrademodule)` | An `[NgModule](../core/ngmodule)`, which you import to provide AngularJS core services, and has an instance method used to bootstrap the hybrid upgrade application. | ### Functions | | | | --- | --- | | `[downgradeComponent](static/downgradecomponent)` | A helper function that allows an Angular component to be used from AngularJS. | | `[downgradeInjectable](static/downgradeinjectable)` | A helper function to allow an Angular service to be accessible from AngularJS. | | `[downgradeModule](static/downgrademodule)` | A helper function for creating an AngularJS module that can bootstrap an Angular module "on-demand" (possibly lazily) when a [downgraded component](static/downgradecomponent) needs to be instantiated. | | `[getAngularJSGlobal](static/getangularjsglobal)` | Returns the current AngularJS global. | | `[getAngularLib](static/getangularlib)` | **Deprecated:** Use `[getAngularJSGlobal](static/getangularjsglobal)` instead. | | `[setAngularJSGlobal](static/setangularjsglobal)` | Resets the AngularJS global. | | `[setAngularLib](static/setangularlib)` | **Deprecated:** Use `[setAngularJSGlobal](static/setangularjsglobal)` instead. | ### Directives | | | | --- | --- | | `[UpgradeComponent](static/upgradecomponent)` | A helper class that allows an AngularJS component to be used from Angular. | angular UpgradeComponent UpgradeComponent ================ `directive` A helper class that allows an AngularJS component to be used from Angular. [See more...](upgradecomponent#description) Description ----------- *Part of the [upgrade/static](api?query=upgrade%2Fstatic) library for hybrid upgrade apps that support AOT compilation.* This helper class should be used as a base class for creating Angular directives that wrap AngularJS components that need to be "upgraded". ### Examples Let's assume that you have an AngularJS component called `ng1Hero` that needs to be made available in Angular templates. ``` // This AngularJS component will be "upgraded" to be used in Angular ng1AppModule.component('ng1Hero', { bindings: {hero: '<', onRemove: '&'}, transclude: true, template: `<div class="title" ng-transclude></div> <h2>{{ $ctrl.hero.name }}</h2> <p>{{ $ctrl.hero.description }}</p> <button ng-click="$ctrl.onRemove()">Remove</button>` }); ``` We must create a `[Directive](../../core/directive)` that will make this AngularJS component available inside Angular templates. ``` // This Angular directive will act as an interface to the "upgraded" AngularJS component @Directive({selector: 'ng1-hero'}) export class Ng1HeroComponentWrapper extends UpgradeComponent { // The names of the input and output properties here must match the names of the // `<` and `&` bindings in the AngularJS component that is being wrapped @Input() hero!: Hero; @Output() onRemove!: EventEmitter<void>; constructor(elementRef: ElementRef, injector: Injector) { // We must pass the name of the directive as used by AngularJS to the super super('ng1Hero', elementRef, injector); } } ``` In this example you can see that we must derive from the `[UpgradeComponent](upgradecomponent)` base class but also provide an [`@Directive`](../../core/directive) decorator. This is because the AOT compiler requires that this information is statically available at compile time. Note that we must do the following: * specify the directive's selector (`ng1-hero`) * specify all inputs and outputs that the AngularJS component expects * derive from `[UpgradeComponent](upgradecomponent)` * call the base class from the constructor, passing + the AngularJS name of the component (`ng1Hero`) + the `[ElementRef](../../core/elementref)` and `[Injector](../../core/injector)` for the component wrapper Methods ------- | ngOnInit() | | --- | | `ngOnInit()` Parameters There are no parameters. | | ngOnChanges() | | --- | | `ngOnChanges(changes: SimpleChanges)` Parameters | | | | | --- | --- | --- | | `changes` | `[SimpleChanges](../../core/simplechanges)` | | | | ngDoCheck() | | --- | | `ngDoCheck()` Parameters There are no parameters. | | ngOnDestroy() | | --- | | `ngOnDestroy()` Parameters There are no parameters. | angular setAngularLib setAngularLib ============= `function` `deprecated` **Deprecated:** Use `[setAngularJSGlobal](setangularjsglobal)` instead. ### `setAngularLib(ng: any): void` **Deprecated** Use `[setAngularJSGlobal](setangularjsglobal)` instead. ###### Parameters | | | | | --- | --- | --- | | `ng` | `any` | | ###### Returns `void` angular getAngularLib getAngularLib ============= `function` `deprecated` **Deprecated:** Use `[getAngularJSGlobal](getangularjsglobal)` instead. ### `getAngularLib(): any` **Deprecated** Use `[getAngularJSGlobal](getangularjsglobal)` instead. ###### Parameters There are no parameters. ###### Returns `any` angular setAngularJSGlobal setAngularJSGlobal ================== `function` Resets the AngularJS global. [See more...](setangularjsglobal#description) ### `setAngularJSGlobal(ng: any): void` ###### Parameters | | | | | --- | --- | --- | | `ng` | `any` | | ###### Returns `void` Description ----------- Used when AngularJS is loaded lazily, and not available on `window`. angular downgradeInjectable downgradeInjectable =================== `function` A helper function to allow an Angular service to be accessible from AngularJS. [See more...](downgradeinjectable#description) ### `downgradeInjectable(token: any, downgradedModule: string = ''): Function` ###### Parameters | | | | | --- | --- | --- | | `token` | `any` | an `[InjectionToken](../../core/injectiontoken)` that identifies a service provided from Angular. | | `downgradedModule` | `string` | the name of the downgraded module (if any) that the injectable "belongs to", as returned by a call to `[downgradeModule](downgrademodule)()`. It is the module, whose injector will be used for instantiating the injectable. (This option is only necessary when using `[downgradeModule](downgrademodule)()` to downgrade more than one Angular module.) Optional. Default is `''`. | ###### Returns `Function`: a [factory function](https://docs.angularjs.org/guide/di) that can be used to register the service on an AngularJS module. Description ----------- *Part of the [upgrade/static](api?query=upgrade%2Fstatic) library for hybrid upgrade apps that support AOT compilation* This helper function returns a factory function that provides access to the Angular service identified by the `token` parameter. Further information is available in the [Usage Notes...](downgradeinjectable#usage-notes) Usage notes ----------- ### Examples First ensure that the service to be downgraded is provided in an `[NgModule](../../core/ngmodule)` that will be part of the upgrade application. For example, let's assume we have defined `HeroesService` ``` // This Angular service will be "downgraded" to be used in AngularJS @Injectable() export class HeroesService { heroes: Hero[] = [ {name: 'superman', description: 'The man of steel'}, {name: 'wonder woman', description: 'Princess of the Amazons'}, {name: 'thor', description: 'The hammer-wielding god'} ]; constructor(textFormatter: TextFormatter) { // Change all the hero names to title case, using the "upgraded" AngularJS service this.heroes.forEach((hero: Hero) => hero.name = textFormatter.titleCase(hero.name)); } addHero() { this.heroes = this.heroes.concat([{name: 'Kamala Khan', description: 'Epic shape-shifting healer'}]); } removeHero(hero: Hero) { this.heroes = this.heroes.filter((item: Hero) => item !== hero); } } ``` and that we have included this in our upgrade app `[NgModule](../../core/ngmodule)` ``` // This NgModule represents the Angular pieces of the application @NgModule({ declarations: [Ng2HeroesComponent, Ng1HeroComponentWrapper], providers: [ HeroesService, // Register an Angular provider whose value is the "upgraded" AngularJS service {provide: TextFormatter, useFactory: (i: any) => i.get('textFormatter'), deps: ['$injector']} ], // We must import `UpgradeModule` to get access to the AngularJS core services imports: [BrowserModule, UpgradeModule] }) export class Ng2AppModule { } ``` Now we can register the `[downgradeInjectable](downgradeinjectable)` factory function for the service on an AngularJS module. ``` // Register an AngularJS service, whose value is the "downgraded" Angular injectable. ng1AppModule.factory('heroesService', downgradeInjectable(HeroesService) as any); ``` Inside an AngularJS component's controller we can get hold of the downgraded service via the name we gave when downgrading. ``` // This is our top level application component ng1AppModule.component('exampleApp', { // We inject the "downgraded" HeroesService into this AngularJS component // (We don't need the `HeroesService` type for AngularJS DI - it just helps with TypeScript // compilation) controller: [ 'heroesService', function(heroesService: HeroesService) { this.heroesService = heroesService; } ], // This template makes use of the downgraded `ng2-heroes` component // Note that because its element is compiled by AngularJS we must use kebab-case attributes // for inputs and outputs template: `<link rel="stylesheet" href="./styles.css"> <ng2-heroes [heroes]="$ctrl.heroesService.heroes" (add-hero)="$ctrl.heroesService.addHero()" (remove-hero)="$ctrl.heroesService.removeHero($event)"> <h1>Heroes</h1> <p class="extra">There are {{ $ctrl.heroesService.heroes.length }} heroes.</p> </ng2-heroes>` }); ``` > When using `[downgradeModule](downgrademodule)()`, downgraded injectables will not be available until the Angular module that provides them is instantiated. In order to be safe, you need to ensure that the downgraded injectables are not used anywhere *outside* the part of the app where it is guaranteed that their module has been instantiated. > > For example, it is *OK* to use a downgraded service in an upgraded component that is only used from a downgraded Angular component provided by the same Angular module as the injectable, but it is *not OK* to use it in an AngularJS component that may be used independently of Angular or use it in a downgraded Angular component from a different module. > > angular downgradeModule downgradeModule =============== `function` A helper function for creating an AngularJS module that can bootstrap an Angular module "on-demand" (possibly lazily) when a [downgraded component](downgradecomponent) needs to be instantiated. [See more...](downgrademodule#description) ### `downgradeModule(moduleOrBootstrapFn: Type<T> | ((extraProviders: StaticProvider[]) => Promise<NgModuleRef<T>>)): string` ###### Parameters | | | | | --- | --- | --- | | `moduleOrBootstrapFn` | `[Type](../../core/type)<T> | ((extraProviders: [StaticProvider](../../core/staticprovider)[]) => Promise<[NgModuleRef](../../core/ngmoduleref)<T>>)` | | ###### Returns `string` ### `downgradeModule(moduleOrBootstrapFn: NgModuleFactory<T>): string` **Deprecated** Passing `[NgModuleFactory](../../core/ngmodulefactory)` as the `[downgradeModule](downgrademodule)` function argument is deprecated, please pass an NgModule class reference instead. ###### Parameters | | | | | --- | --- | --- | | `moduleOrBootstrapFn` | `[NgModuleFactory<T>](../../core/ngmodulefactory)` | | ###### Returns `string` Description ----------- *Part of the [upgrade/static](api?query=upgrade/static) library for hybrid upgrade apps that support AOT compilation.* It allows loading/bootstrapping the Angular part of a hybrid application lazily and not having to pay the cost up-front. For example, you can have an AngularJS application that uses Angular for specific routes and only instantiate the Angular modules if/when the user visits one of these routes. The Angular module will be bootstrapped once (when requested for the first time) and the same reference will be used from that point onwards. `[downgradeModule](downgrademodule)()` requires either an `[NgModuleFactory](../../core/ngmodulefactory)`, `[NgModule](../../core/ngmodule)` class or a function: * `[NgModuleFactory](../../core/ngmodulefactory)`: If you pass an `[NgModuleFactory](../../core/ngmodulefactory)`, it will be used to instantiate a module using `[platformBrowser](../../platform-browser/platformbrowser)`'s [bootstrapModuleFactory()](../../core/platformref#bootstrapModuleFactory). NOTE: this type of the argument is deprecated. Please either provide an `[NgModule](../../core/ngmodule)` class or a bootstrap function instead. * `[NgModule](../../core/ngmodule)` class: If you pass an NgModule class, it will be used to instantiate a module using `[platformBrowser](../../platform-browser/platformbrowser)`'s [bootstrapModule()](../../core/platformref#bootstrapModule). * `Function`: If you pass a function, it is expected to return a promise resolving to an `[NgModuleRef](../../core/ngmoduleref)`. The function is called with an array of extra [Providers](../../core/staticprovider) that are expected to be available from the returned `[NgModuleRef](../../core/ngmoduleref)`'s `[Injector](../../core/injector)`. `[downgradeModule](downgrademodule)()` returns the name of the created AngularJS wrapper module. You can use it to declare a dependency in your main AngularJS module. ``` import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {downgradeComponent, downgradeModule, UpgradeComponent} from '@angular/upgrade/static'; // The function that will bootstrap the Angular module (when/if necessary). // (This would be omitted if we provided an `NgModuleFactory` directly.) const ng2BootstrapFn = (extraProviders: StaticProvider[]) => platformBrowserDynamic(extraProviders).bootstrapModule(MyLazyAngularModule); // This AngularJS module represents the AngularJS pieces of the application. const myMainAngularJsModule = angular.module('myMainAngularJsModule', [ // We declare a dependency on the "downgraded" Angular module. downgradeModule(ng2BootstrapFn) // or // downgradeModule(MyLazyAngularModuleFactory) ]); ``` For more details on how to use `[downgradeModule](downgrademodule)()` see [Upgrading for Performance](../../../guide/upgrade-performance). Further information is available in the [Usage Notes...](downgrademodule#usage-notes) Usage notes ----------- Apart from `[UpgradeModule](upgrademodule)`, you can use the rest of the `[upgrade/static](../static)` helpers as usual to build a hybrid application. Note that the Angular pieces (e.g. downgraded services) will not be available until the downgraded module has been bootstrapped, i.e. by instantiating a downgraded component. > You cannot use `[downgradeModule](downgrademodule)()` and `[UpgradeModule](upgrademodule)` in the same hybrid application. Use one or the other. > > ### Differences with `[UpgradeModule](upgrademodule)` Besides their different API, there are two important internal differences between `[downgradeModule](downgrademodule)()` and `[UpgradeModule](upgrademodule)` that affect the behavior of hybrid applications: 1. Unlike `[UpgradeModule](upgrademodule)`, `[downgradeModule](downgrademodule)()` does not bootstrap the main AngularJS module inside the [Angular zone](../../core/ngzone). 2. Unlike `[UpgradeModule](upgrademodule)`, `[downgradeModule](downgrademodule)()` does not automatically run a [$digest()](https://docs.angularjs.org/api/ng/type/%24rootScope.Scope#%24digest) when changes are detected in the Angular part of the application. What this means is that applications using `[UpgradeModule](upgrademodule)` will run change detection more frequently in order to ensure that both frameworks are properly notified about possible changes. This will inevitably result in more change detection runs than necessary. `[downgradeModule](downgrademodule)()`, on the other side, does not try to tie the two change detection systems as tightly, restricting the explicit change detection runs only to cases where it knows it is necessary (e.g. when the inputs of a downgraded component change). This improves performance, especially in change-detection-heavy applications, but leaves it up to the developer to manually notify each framework as needed. For a more detailed discussion of the differences and their implications, see [Upgrading for Performance](../../../guide/upgrade-performance). > You can manually trigger a change detection run in AngularJS using [scope.$apply(...)](https://docs.angularjs.org/api/ng/type/%24rootScope.Scope#%24apply) or [$rootScope.$digest()](https://docs.angularjs.org/api/ng/type/%24rootScope.Scope#%24digest). > > You can manually trigger a change detection run in Angular using [ngZone.run(...)](../../core/ngzone#run). > > ### Downgrading multiple modules It is possible to downgrade multiple modules and include them in an AngularJS application. In that case, each downgraded module will be bootstrapped when an associated downgraded component or injectable needs to be instantiated. Things to keep in mind, when downgrading multiple modules: * Each downgraded component/injectable needs to be explicitly associated with a downgraded module. See `[downgradeComponent](downgradecomponent)()` and `[downgradeInjectable](downgradeinjectable)()` for more details. * If you want some injectables to be shared among all downgraded modules, you can provide them as `[StaticProvider](../../core/staticprovider)`s, when creating the `[PlatformRef](../../core/platformref)` (e.g. via `[platformBrowser](../../platform-browser/platformbrowser)` or `[platformBrowserDynamic](../../platform-browser-dynamic/platformbrowserdynamic)`). * When using [`bootstrapModule()`](../../core/platformref#bootstrapmodule) or [`bootstrapModuleFactory()`](../../core/platformref#bootstrapmodulefactory) to bootstrap the downgraded modules, each one is considered a "root" module. As a consequence, a new instance will be created for every injectable provided in `"root"` (via [`providedIn`](../../core/injectable#providedIn)). If this is not your intention, you can have a shared module (that will act as act as the "root" module) and create all downgraded modules using that module's injector: ``` let rootInjectorPromise: Promise<Injector>|null = null; const getRootInjector = (extraProviders: StaticProvider[]) => { if (!rootInjectorPromise) { rootInjectorPromise = platformBrowserDynamic(extraProviders) .bootstrapModule(Ng2RootModule) .then(moduleRef => moduleRef.injector); } return rootInjectorPromise; }; const downgradedNg2AModule = downgradeModule(async (extraProviders: StaticProvider[]) => { const rootInjector = await getRootInjector(extraProviders); const moduleAFactory = await rootInjector.get(Compiler).compileModuleAsync(Ng2AModule); return moduleAFactory.create(rootInjector); }); const downgradedNg2BModule = downgradeModule(async (extraProviders: StaticProvider[]) => { const rootInjector = await getRootInjector(extraProviders); const moduleBFactory = await rootInjector.get(Compiler).compileModuleAsync(Ng2BModule); return moduleBFactory.create(rootInjector); }); /* . . . */ const appModule = angular .module( 'exampleAppModule', [downgradedNg2AModule, downgradedNg2BModule, downgradedNg2CModule]) ```
programming_docs
angular getAngularJSGlobal getAngularJSGlobal ================== `function` Returns the current AngularJS global. ### `getAngularJSGlobal(): any` ###### Parameters There are no parameters. ###### Returns `any` angular downgradeComponent downgradeComponent ================== `function` A helper function that allows an Angular component to be used from AngularJS. [See more...](downgradecomponent#description) ### `downgradeComponent(info: { component: Type<any>; downgradedModule?: string; propagateDigest?: boolean; inputs?: string[]; outputs?: string[]; selectors?: string[]; }): any` ###### Parameters | | | | | --- | --- | --- | | `info` | `object` | contains information about the Component that is being downgraded:* `component: [Type](../../core/type)<any>`: The type of the Component that will be downgraded * `downgradedModule?: string`: The name of the downgraded module (if any) that the component "belongs to", as returned by a call to `[downgradeModule](downgrademodule)()`. It is the module, whose corresponding Angular module will be bootstrapped, when the component needs to be instantiated. (This option is only necessary when using `[downgradeModule](downgrademodule)()` to downgrade more than one Angular module.) * `propagateDigest?: boolean`: Whether to perform [change detection](../../core/changedetectorref#detectChanges) on the component on every [$digest](https://docs.angularjs.org/api/ng/type/%24rootScope.Scope#%24digest). If set to `false`, change detection will still be performed when any of the component's inputs changes. (Default: true) | ###### Returns `any`: a factory function that can be used to register the component in an AngularJS module. Description ----------- *Part of the [upgrade/static](api?query=upgrade%2Fstatic) library for hybrid upgrade apps that support AOT compilation* This helper function returns a factory function to be used for registering an AngularJS wrapper directive for "downgrading" an Angular component. Further information is available in the [Usage Notes...](downgradecomponent#usage-notes) Usage notes ----------- ### Examples Let's assume that you have an Angular component called `ng2Heroes` that needs to be made available in AngularJS templates. ``` // This Angular component will be "downgraded" to be used in AngularJS @Component({ selector: 'ng2-heroes', // This template uses the upgraded `ng1-hero` component // Note that because its element is compiled by Angular we must use camelCased attribute names template: `<header><ng-content selector="h1"></ng-content></header> <ng-content selector=".extra"></ng-content> <div *ngFor="let hero of heroes"> <ng1-hero [hero]="hero" (onRemove)="removeHero.emit(hero)"><strong>Super Hero</strong></ng1-hero> </div> <button (click)="addHero.emit()">Add Hero</button>`, }) export class Ng2HeroesComponent { @Input() heroes!: Hero[]; @Output() addHero = new EventEmitter(); @Output() removeHero = new EventEmitter(); } ``` We must create an AngularJS [directive](https://docs.angularjs.org/guide/directive) that will make this Angular component available inside AngularJS templates. The `[downgradeComponent](downgradecomponent)()` function returns a factory function that we can use to define the AngularJS directive that wraps the "downgraded" component. ``` // This directive will act as the interface to the "downgraded" Angular component ng1AppModule.directive('ng2Heroes', downgradeComponent({component: Ng2HeroesComponent})); ``` For more details and examples on downgrading Angular components to AngularJS components please visit the [Upgrade guide](../../../guide/upgrade#using-angular-components-from-angularjs-code). angular @angular/upgrade/static/testing @angular/upgrade/static/testing =============================== `entry-point` Supplies testing functions for the AngularJS-to-Angular upgrade path. Entry point exports ------------------- ### Functions | | | | --- | --- | | `[createAngularJSTestingModule](testing/createangularjstestingmodule)` | A helper function to use when unit testing AngularJS services that depend upon downgraded Angular services. | | `[createAngularTestingModule](testing/createangulartestingmodule)` | A helper function to use when unit testing Angular services that depend upon upgraded AngularJS services. | angular UpgradeModule UpgradeModule ============= `ngmodule` An `[NgModule](../../core/ngmodule)`, which you import to provide AngularJS core services, and has an instance method used to bootstrap the hybrid upgrade application. [See more...](upgrademodule#description) ``` class UpgradeModule { $injector: any injector: Injector ngZone: NgZone bootstrap(element: Element, modules: string[] = [], config?: any): any } ``` Description ----------- *Part of the [upgrade/static](api?query=upgrade/static) library for hybrid upgrade apps that support AOT compilation* The `[upgrade/static](../static)` package contains helpers that allow AngularJS and Angular components to be used together inside a hybrid upgrade application, which supports AOT compilation. Specifically, the classes and functions in the `[upgrade/static](../static)` module allow the following: 1. Creation of an Angular directive that wraps and exposes an AngularJS component so that it can be used in an Angular template. See `[UpgradeComponent](upgradecomponent)`. 2. Creation of an AngularJS directive that wraps and exposes an Angular component so that it can be used in an AngularJS template. See `[downgradeComponent](downgradecomponent)`. 3. Creation of an Angular root injector provider that wraps and exposes an AngularJS service so that it can be injected into an Angular context. See [Upgrading an AngularJS service](upgrademodule#upgrading-an-angular-1-service) below. 4. Creation of an AngularJS service that wraps and exposes an Angular injectable so that it can be injected into an AngularJS context. See `[downgradeInjectable](downgradeinjectable)`. 5. Bootstrapping of a hybrid Angular application which contains both of the frameworks coexisting in a single application. Further information is available in the [Usage Notes...](upgrademodule#usage-notes) Properties ---------- | Property | Description | | --- | --- | | `$injector: any` | The AngularJS `$injector` for the upgrade application. | | `injector: [Injector](../../core/injector)` | The Angular Injector \* | | `ngZone: [NgZone](../../core/ngzone)` | The bootstrap zone for the upgrade application | Methods ------- | bootstrap() | | --- | | Bootstrap an AngularJS application from this NgModule | | `bootstrap(element: Element, modules: string[] = [], config?: any): any` Parameters | | | | | --- | --- | --- | | `element` | `Element` | the element on which to bootstrap the AngularJS application | | `modules` | `string[]` | the AngularJS modules to bootstrap for this application Optional. Default is `[]`. | | `config` | `any` | optional extra AngularJS bootstrap configuration Optional. Default is `undefined`. | Returns `any`: The value returned by [angular.bootstrap()](https://docs.angularjs.org/api/ng/function/angular.bootstrap). | Providers --------- | Provider | | --- | | ``` angular1Providers ``` | Usage notes ----------- ``` import {UpgradeModule} from '@angular/upgrade/static'; ``` See also the [examples](upgrademodule#examples) below. ### Mental Model When reasoning about how a hybrid application works it is useful to have a mental model which describes what is happening and explains what is happening at the lowest level. 1. There are two independent frameworks running in a single application, each framework treats the other as a black box. 2. Each DOM element on the page is owned exactly by one framework. Whichever framework instantiated the element is the owner. Each framework only updates/interacts with its own DOM elements and ignores others. 3. AngularJS directives always execute inside the AngularJS framework codebase regardless of where they are instantiated. 4. Angular components always execute inside the Angular framework codebase regardless of where they are instantiated. 5. An AngularJS component can be "upgraded"" to an Angular component. This is achieved by defining an Angular directive, which bootstraps the AngularJS component at its location in the DOM. See `[UpgradeComponent](upgradecomponent)`. 6. An Angular component can be "downgraded" to an AngularJS component. This is achieved by defining an AngularJS directive, which bootstraps the Angular component at its location in the DOM. See `[downgradeComponent](downgradecomponent)`. 7. Whenever an "upgraded"/"downgraded" component is instantiated the host element is owned by the framework doing the instantiation. The other framework then instantiates and owns the view for that component. 1. This implies that the component bindings will always follow the semantics of the instantiation framework. 2. The DOM attributes are parsed by the framework that owns the current template. So attributes in AngularJS templates must use kebab-case, while AngularJS templates must use camelCase. 3. However the template binding syntax will always use the Angular style, e.g. square brackets (`[...]`) for property binding. 8. Angular is bootstrapped first; AngularJS is bootstrapped second. AngularJS always owns the root component of the application. 9. The new application is running in an Angular zone, and therefore it no longer needs calls to `$apply()`. ### The `[UpgradeModule](upgrademodule)` class This class is an `[NgModule](../../core/ngmodule)`, which you import to provide AngularJS core services, and has an instance method used to bootstrap the hybrid upgrade application. * Core AngularJS services Importing this `[NgModule](../../core/ngmodule)` will add providers for the core [AngularJS services](https://docs.angularjs.org/api/ng/service) to the root injector. * Bootstrap The runtime instance of this class contains a [`bootstrap()`](upgrademodule#bootstrap) method, which you use to bootstrap the top level AngularJS module onto an element in the DOM for the hybrid upgrade app. It also contains properties to access the [root injector](upgrademodule#injector), the bootstrap `[NgZone](../../core/ngzone)` and the [AngularJS $injector](https://docs.angularjs.org/api/auto/service/%24injector). ### Examples Import the `[UpgradeModule](upgrademodule)` into your top level [Angular `NgModule`](../../core/ngmodule). ``` // This NgModule represents the Angular pieces of the application @NgModule({ declarations: [Ng2HeroesComponent, Ng1HeroComponentWrapper], providers: [ HeroesService, // Register an Angular provider whose value is the "upgraded" AngularJS service {provide: TextFormatter, useFactory: (i: any) => i.get('textFormatter'), deps: ['$injector']} ], // We must import `UpgradeModule` to get access to the AngularJS core services imports: [BrowserModule, UpgradeModule] }) export class Ng2AppModule { } ``` Then inject `[UpgradeModule](upgrademodule)` into your Angular `[NgModule](../../core/ngmodule)` and use it to bootstrap the top level [AngularJS module](https://docs.angularjs.org/api/ng/type/angular.Module) in the `ngDoBootstrap()` method. ``` export class Ng2AppModule { constructor(private upgrade: UpgradeModule) {} ngDoBootstrap() { // We bootstrap the AngularJS app. this.upgrade.bootstrap(document.body, [ng1AppModule.name]); } } ``` Finally, kick off the whole process, by bootstrapping your top level Angular `[NgModule](../../core/ngmodule)`. ``` // We bootstrap the Angular module as we would do in a normal Angular app. // (We are using the dynamic browser platform as this example has not been compiled AOT.) platformBrowserDynamic().bootstrapModule(Ng2AppModule); ``` ### Upgrading an AngularJS service There is no specific API for upgrading an AngularJS service. Instead you should just follow the following recipe: Let's say you have an AngularJS service: ``` export class TextFormatter { titleCase(value: string) { return value.replace(/((^|\s)[a-z])/g, (_, c) => c.toUpperCase()); } } // This AngularJS service will be "upgraded" to be used in Angular ng1AppModule.service('textFormatter', [TextFormatter]); ``` Then you should define an Angular provider to be included in your `[NgModule](../../core/ngmodule)` `providers` property. ``` // Register an Angular provider whose value is the "upgraded" AngularJS service {provide: TextFormatter, useFactory: (i: any) => i.get('textFormatter'), deps: ['$injector']} ``` Then you can use the "upgraded" AngularJS service by injecting it into an Angular component or service. ``` constructor(textFormatter: TextFormatter) { // Change all the hero names to title case, using the "upgraded" AngularJS service this.heroes.forEach((hero: Hero) => hero.name = textFormatter.titleCase(hero.name)); } ``` angular createAngularJSTestingModule createAngularJSTestingModule ============================ `function` A helper function to use when unit testing AngularJS services that depend upon downgraded Angular services. [See more...](createangularjstestingmodule#description) ### `createAngularJSTestingModule(angularModules: any[]): string` ###### Parameters | | | | | --- | --- | --- | | `angularModules` | `any[]` | a collection of Angular modules to include in the configuration. | ###### Returns `string` Description ----------- This function returns an AngularJS module that is configured to wire up the AngularJS and Angular injectors without the need to actually bootstrap a hybrid application. This makes it simpler and faster to unit test services. Use the returned AngularJS module in a call to [`angular.mocks.module`](https://docs.angularjs.org/api/ngMock/function/angular.mock.module) to include this module in the unit test injector. In the following code snippet, we are configuring the `$injector` with two modules: The AngularJS `ng1AppModule`, which is the AngularJS part of our hybrid application and the `Ng2AppModule`, which is the Angular part. ``` beforeEach(module(createAngularJSTestingModule([Ng2AppModule]))); beforeEach(module(ng1AppModule.name)); ``` Once this is done we can get hold of services via the AngularJS `$injector` as normal. Services that are (or have dependencies on) a downgraded Angular service, will be instantiated as needed by the Angular root `[Injector](../../../core/injector)`. In the following code snippet, `heroesService` is a downgraded Angular service that we are accessing from AngularJS. ``` it('should have access to the HeroesService', inject((heroesService: HeroesService) => { expect(heroesService).toBeDefined(); })); ``` > This helper is for testing services not components. For Component testing you must still bootstrap a hybrid app. See `[UpgradeModule](../upgrademodule)` or `[downgradeModule](../downgrademodule)` for more information. > > > The resulting configuration does not wire up AngularJS digests to Zone hooks. It is the responsibility of the test writer to call `$rootScope.$apply`, as necessary, to trigger AngularJS handlers of async events from Angular. > > > The helper sets up global variables to hold the shared Angular and AngularJS injectors. > > * Only call this helper once per spec. > * Do not use `[createAngularJSTestingModule](createangularjstestingmodule)` in the same spec as `[createAngularTestingModule](createangulartestingmodule)`. > > Here is the example application and its unit tests that use `[createAngularTestingModule](createangulartestingmodule)` and `[createAngularJSTestingModule](createangularjstestingmodule)`. ``` /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {TestBed} from '@angular/core/testing'; import {createAngularJSTestingModule, createAngularTestingModule} from '@angular/upgrade/static/testing'; import {HeroesService, ng1AppModule, Ng2AppModule} from './module'; const {module, inject} = (window as any).angular.mock; describe('HeroesService (from Angular)', () => { beforeEach(() => { TestBed.configureTestingModule( {imports: [createAngularTestingModule([ng1AppModule.name]), Ng2AppModule]}); }); it('should have access to the HeroesService', () => { const heroesService = TestBed.inject(HeroesService); expect(heroesService).toBeDefined(); }); }); describe('HeroesService (from AngularJS)', () => { beforeEach(module(createAngularJSTestingModule([Ng2AppModule]))); beforeEach(module(ng1AppModule.name)); it('should have access to the HeroesService', inject((heroesService: HeroesService) => { expect(heroesService).toBeDefined(); })); }); ``` ``` /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Component, Directive, ElementRef, EventEmitter, Injectable, Injector, Input, NgModule, Output} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {downgradeComponent, downgradeInjectable, UpgradeComponent, UpgradeModule} from '@angular/upgrade/static'; declare var angular: ng.IAngularStatic; export interface Hero { name: string; description: string; } export class TextFormatter { titleCase(value: string) { return value.replace(/((^|\s)[a-z])/g, (_, c) => c.toUpperCase()); } } // This Angular component will be "downgraded" to be used in AngularJS @Component({ selector: 'ng2-heroes', // This template uses the upgraded `ng1-hero` component // Note that because its element is compiled by Angular we must use camelCased attribute names template: `<header><ng-content selector="h1"></ng-content></header> <ng-content selector=".extra"></ng-content> <div *ngFor="let hero of heroes"> <ng1-hero [hero]="hero" (onRemove)="removeHero.emit(hero)"><strong>Super Hero</strong></ng1-hero> </div> <button (click)="addHero.emit()">Add Hero</button>`, }) export class Ng2HeroesComponent { @Input() heroes!: Hero[]; @Output() addHero = new EventEmitter(); @Output() removeHero = new EventEmitter(); } // This Angular service will be "downgraded" to be used in AngularJS @Injectable() export class HeroesService { heroes: Hero[] = [ {name: 'superman', description: 'The man of steel'}, {name: 'wonder woman', description: 'Princess of the Amazons'}, {name: 'thor', description: 'The hammer-wielding god'} ]; constructor(textFormatter: TextFormatter) { // Change all the hero names to title case, using the "upgraded" AngularJS service this.heroes.forEach((hero: Hero) => hero.name = textFormatter.titleCase(hero.name)); } addHero() { this.heroes = this.heroes.concat([{name: 'Kamala Khan', description: 'Epic shape-shifting healer'}]); } removeHero(hero: Hero) { this.heroes = this.heroes.filter((item: Hero) => item !== hero); } } // This Angular directive will act as an interface to the "upgraded" AngularJS component @Directive({selector: 'ng1-hero'}) export class Ng1HeroComponentWrapper extends UpgradeComponent { // The names of the input and output properties here must match the names of the // `<` and `&` bindings in the AngularJS component that is being wrapped @Input() hero!: Hero; @Output() onRemove!: EventEmitter<void>; constructor(elementRef: ElementRef, injector: Injector) { // We must pass the name of the directive as used by AngularJS to the super super('ng1Hero', elementRef, injector); } } // This NgModule represents the Angular pieces of the application @NgModule({ declarations: [Ng2HeroesComponent, Ng1HeroComponentWrapper], providers: [ HeroesService, // Register an Angular provider whose value is the "upgraded" AngularJS service {provide: TextFormatter, useFactory: (i: any) => i.get('textFormatter'), deps: ['$injector']} ], // We must import `UpgradeModule` to get access to the AngularJS core services imports: [BrowserModule, UpgradeModule] }) export class Ng2AppModule { constructor(private upgrade: UpgradeModule) {} ngDoBootstrap() { // We bootstrap the AngularJS app. this.upgrade.bootstrap(document.body, [ng1AppModule.name]); } } // This Angular 1 module represents the AngularJS pieces of the application export const ng1AppModule: ng.IModule = angular.module('ng1AppModule', []); // This AngularJS component will be "upgraded" to be used in Angular ng1AppModule.component('ng1Hero', { bindings: {hero: '<', onRemove: '&'}, transclude: true, template: `<div class="title" ng-transclude></div> <h2>{{ $ctrl.hero.name }}</h2> <p>{{ $ctrl.hero.description }}</p> <button ng-click="$ctrl.onRemove()">Remove</button>` }); // This AngularJS service will be "upgraded" to be used in Angular ng1AppModule.service('textFormatter', [TextFormatter]); // Register an AngularJS service, whose value is the "downgraded" Angular injectable. ng1AppModule.factory('heroesService', downgradeInjectable(HeroesService) as any); // This directive will act as the interface to the "downgraded" Angular component ng1AppModule.directive('ng2Heroes', downgradeComponent({component: Ng2HeroesComponent})); // This is our top level application component ng1AppModule.component('exampleApp', { // We inject the "downgraded" HeroesService into this AngularJS component // (We don't need the `HeroesService` type for AngularJS DI - it just helps with TypeScript // compilation) controller: [ 'heroesService', function(heroesService: HeroesService) { this.heroesService = heroesService; } ], // This template makes use of the downgraded `ng2-heroes` component // Note that because its element is compiled by AngularJS we must use kebab-case attributes // for inputs and outputs template: `<link rel="stylesheet" href="./styles.css"> <ng2-heroes [heroes]="$ctrl.heroesService.heroes" (add-hero)="$ctrl.heroesService.addHero()" (remove-hero)="$ctrl.heroesService.removeHero($event)"> <h1>Heroes</h1> <p class="extra">There are {{ $ctrl.heroesService.heroes.length }} heroes.</p> </ng2-heroes>` }); // We bootstrap the Angular module as we would do in a normal Angular app. // (We are using the dynamic browser platform as this example has not been compiled AOT.) platformBrowserDynamic().bootstrapModule(Ng2AppModule); ```
programming_docs
angular createAngularTestingModule createAngularTestingModule ========================== `function` A helper function to use when unit testing Angular services that depend upon upgraded AngularJS services. [See more...](createangulartestingmodule#description) ### `createAngularTestingModule(angularJSModules: string[], strictDi?: boolean): Type<any>` ###### Parameters | | | | | --- | --- | --- | | `angularJSModules` | `string[]` | a collection of the names of AngularJS modules to include in the configuration. | | `strictDi` | `boolean` | whether the AngularJS injector should have `strictDI` enabled. Optional. Default is `undefined`. | ###### Returns `[Type](../../../core/type)<any>` Description ----------- This function returns an `[NgModule](../../../core/ngmodule)` decorated class that is configured to wire up the Angular and AngularJS injectors without the need to actually bootstrap a hybrid application. This makes it simpler and faster to unit test services. Use the returned class as an "import" when configuring the `[TestBed](../../../core/testing/testbed)`. In the following code snippet, we are configuring the TestBed with two imports. The `Ng2AppModule` is the Angular part of our hybrid application and the `ng1AppModule` is the AngularJS part. ``` import {TestBed} from '@angular/core/testing'; import {createAngularJSTestingModule, createAngularTestingModule} from '@angular/upgrade/static/testing'; import {HeroesService, ng1AppModule, Ng2AppModule} from './module'; const {module, inject} = (window as any).angular.mock; /* . . . */ beforeEach(() => { TestBed.configureTestingModule( {imports: [createAngularTestingModule([ng1AppModule.name]), Ng2AppModule]}); }); ``` Once this is done we can get hold of services via the Angular `[Injector](../../../core/injector)` as normal. Services that are (or have dependencies on) an upgraded AngularJS service, will be instantiated as needed by the AngularJS `$injector`. In the following code snippet, `HeroesService` is an Angular service that depends upon an AngularJS service, `titleCase`. ``` it('should have access to the HeroesService', () => { const heroesService = TestBed.inject(HeroesService); expect(heroesService).toBeDefined(); }); ``` > This helper is for testing services not Components. For Component testing you must still bootstrap a hybrid app. See `[UpgradeModule](../upgrademodule)` or `[downgradeModule](../downgrademodule)` for more information. > > > The resulting configuration does not wire up AngularJS digests to Zone hooks. It is the responsibility of the test writer to call `$rootScope.$apply`, as necessary, to trigger AngularJS handlers of async events from Angular. > > > The helper sets up global variables to hold the shared Angular and AngularJS injectors. > > * Only call this helper once per spec. > * Do not use `[createAngularTestingModule](createangulartestingmodule)` in the same spec as `[createAngularJSTestingModule](createangularjstestingmodule)`. > > Here is the example application and its unit tests that use `[createAngularTestingModule](createangulartestingmodule)` and `[createAngularJSTestingModule](createangularjstestingmodule)`. ``` /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {TestBed} from '@angular/core/testing'; import {createAngularJSTestingModule, createAngularTestingModule} from '@angular/upgrade/static/testing'; import {HeroesService, ng1AppModule, Ng2AppModule} from './module'; const {module, inject} = (window as any).angular.mock; describe('HeroesService (from Angular)', () => { beforeEach(() => { TestBed.configureTestingModule( {imports: [createAngularTestingModule([ng1AppModule.name]), Ng2AppModule]}); }); it('should have access to the HeroesService', () => { const heroesService = TestBed.inject(HeroesService); expect(heroesService).toBeDefined(); }); }); describe('HeroesService (from AngularJS)', () => { beforeEach(module(createAngularJSTestingModule([Ng2AppModule]))); beforeEach(module(ng1AppModule.name)); it('should have access to the HeroesService', inject((heroesService: HeroesService) => { expect(heroesService).toBeDefined(); })); }); ``` ``` /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Component, Directive, ElementRef, EventEmitter, Injectable, Injector, Input, NgModule, Output} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {downgradeComponent, downgradeInjectable, UpgradeComponent, UpgradeModule} from '@angular/upgrade/static'; declare var angular: ng.IAngularStatic; export interface Hero { name: string; description: string; } export class TextFormatter { titleCase(value: string) { return value.replace(/((^|\s)[a-z])/g, (_, c) => c.toUpperCase()); } } // This Angular component will be "downgraded" to be used in AngularJS @Component({ selector: 'ng2-heroes', // This template uses the upgraded `ng1-hero` component // Note that because its element is compiled by Angular we must use camelCased attribute names template: `<header><ng-content selector="h1"></ng-content></header> <ng-content selector=".extra"></ng-content> <div *ngFor="let hero of heroes"> <ng1-hero [hero]="hero" (onRemove)="removeHero.emit(hero)"><strong>Super Hero</strong></ng1-hero> </div> <button (click)="addHero.emit()">Add Hero</button>`, }) export class Ng2HeroesComponent { @Input() heroes!: Hero[]; @Output() addHero = new EventEmitter(); @Output() removeHero = new EventEmitter(); } // This Angular service will be "downgraded" to be used in AngularJS @Injectable() export class HeroesService { heroes: Hero[] = [ {name: 'superman', description: 'The man of steel'}, {name: 'wonder woman', description: 'Princess of the Amazons'}, {name: 'thor', description: 'The hammer-wielding god'} ]; constructor(textFormatter: TextFormatter) { // Change all the hero names to title case, using the "upgraded" AngularJS service this.heroes.forEach((hero: Hero) => hero.name = textFormatter.titleCase(hero.name)); } addHero() { this.heroes = this.heroes.concat([{name: 'Kamala Khan', description: 'Epic shape-shifting healer'}]); } removeHero(hero: Hero) { this.heroes = this.heroes.filter((item: Hero) => item !== hero); } } // This Angular directive will act as an interface to the "upgraded" AngularJS component @Directive({selector: 'ng1-hero'}) export class Ng1HeroComponentWrapper extends UpgradeComponent { // The names of the input and output properties here must match the names of the // `<` and `&` bindings in the AngularJS component that is being wrapped @Input() hero!: Hero; @Output() onRemove!: EventEmitter<void>; constructor(elementRef: ElementRef, injector: Injector) { // We must pass the name of the directive as used by AngularJS to the super super('ng1Hero', elementRef, injector); } } // This NgModule represents the Angular pieces of the application @NgModule({ declarations: [Ng2HeroesComponent, Ng1HeroComponentWrapper], providers: [ HeroesService, // Register an Angular provider whose value is the "upgraded" AngularJS service {provide: TextFormatter, useFactory: (i: any) => i.get('textFormatter'), deps: ['$injector']} ], // We must import `UpgradeModule` to get access to the AngularJS core services imports: [BrowserModule, UpgradeModule] }) export class Ng2AppModule { constructor(private upgrade: UpgradeModule) {} ngDoBootstrap() { // We bootstrap the AngularJS app. this.upgrade.bootstrap(document.body, [ng1AppModule.name]); } } // This Angular 1 module represents the AngularJS pieces of the application export const ng1AppModule: ng.IModule = angular.module('ng1AppModule', []); // This AngularJS component will be "upgraded" to be used in Angular ng1AppModule.component('ng1Hero', { bindings: {hero: '<', onRemove: '&'}, transclude: true, template: `<div class="title" ng-transclude></div> <h2>{{ $ctrl.hero.name }}</h2> <p>{{ $ctrl.hero.description }}</p> <button ng-click="$ctrl.onRemove()">Remove</button>` }); // This AngularJS service will be "upgraded" to be used in Angular ng1AppModule.service('textFormatter', [TextFormatter]); // Register an AngularJS service, whose value is the "downgraded" Angular injectable. ng1AppModule.factory('heroesService', downgradeInjectable(HeroesService) as any); // This directive will act as the interface to the "downgraded" Angular component ng1AppModule.directive('ng2Heroes', downgradeComponent({component: Ng2HeroesComponent})); // This is our top level application component ng1AppModule.component('exampleApp', { // We inject the "downgraded" HeroesService into this AngularJS component // (We don't need the `HeroesService` type for AngularJS DI - it just helps with TypeScript // compilation) controller: [ 'heroesService', function(heroesService: HeroesService) { this.heroesService = heroesService; } ], // This template makes use of the downgraded `ng2-heroes` component // Note that because its element is compiled by AngularJS we must use kebab-case attributes // for inputs and outputs template: `<link rel="stylesheet" href="./styles.css"> <ng2-heroes [heroes]="$ctrl.heroesService.heroes" (add-hero)="$ctrl.heroesService.addHero()" (remove-hero)="$ctrl.heroesService.removeHero($event)"> <h1>Heroes</h1> <p class="extra">There are {{ $ctrl.heroesService.heroes.length }} heroes.</p> </ng2-heroes>` }); // We bootstrap the Angular module as we would do in a normal Angular app. // (We are using the dynamic browser platform as this example has not been compiled AOT.) platformBrowserDynamic().bootstrapModule(Ng2AppModule); ``` angular RangeValueAccessor RangeValueAccessor ================== `directive` The `[ControlValueAccessor](controlvalueaccessor)` for writing a range value and listening to range input changes. The value accessor is used by the `[FormControlDirective](formcontroldirective)`, `[FormControlName](formcontrolname)`, and `[NgModel](ngmodel)` directives. Exported from ------------- * [``` ReactiveFormsModule ```](reactiveformsmodule) * [``` FormsModule ```](formsmodule) Selectors --------- * `input[type=range][[formControlName](formcontrolname)]` * `input[type=range][formControl]` * `input[type=range][[ngModel](ngmodel)]` Description ----------- ### Using a range input with a reactive form The following example shows how to use a range input with a reactive form. ``` const ageControl = new FormControl(); ``` ``` <input type="range" [formControl]="ageControl"> ``` angular NgSelectOption NgSelectOption ============== `directive` Marks `<option>` as dynamic, so Angular can be notified when options change. See also -------- * `[SelectControlValueAccessor](selectcontrolvalueaccessor)` Exported from ------------- * [``` ReactiveFormsModule ```](reactiveformsmodule) * [``` FormsModule ```](formsmodule) Selectors --------- * `option` Properties ---------- | Property | Description | | --- | --- | | `id: string` | ID of the option element | | `@[Input](../core/input)()ngValue: any` | Write-Only Tracks the value bound to the option element. Unlike the value binding, ngValue supports binding to objects. | | `@[Input](../core/input)()value: any` | Write-Only Tracks simple string values bound to the option element. For objects, use the `ngValue` input binding. | angular isFormArray isFormArray =========== `const` Asserts that the given control is an instance of `[FormArray](formarray)` ### `const isFormArray: (control: unknown) => control is FormArray<any>;` angular ControlValueAccessor ControlValueAccessor ==================== `interface` Defines an interface that acts as a bridge between the Angular forms API and a native element in the DOM. [See more...](controlvalueaccessor#description) ``` interface ControlValueAccessor { writeValue(obj: any): void registerOnChange(fn: any): void registerOnTouched(fn: any): void setDisabledState(isDisabled: boolean)?: void } ``` Class implementations --------------------- * `[CheckboxControlValueAccessor](checkboxcontrolvalueaccessor)` * `[DefaultValueAccessor](defaultvalueaccessor)` * `[NumberValueAccessor](numbervalueaccessor)` * `[RadioControlValueAccessor](radiocontrolvalueaccessor)` * `[RangeValueAccessor](rangevalueaccessor)` * `[SelectControlValueAccessor](selectcontrolvalueaccessor)` * `[SelectMultipleControlValueAccessor](selectmultiplecontrolvalueaccessor)` See also -------- * DefaultValueAccessor Description ----------- Implement this interface to create a custom form control directive that integrates with Angular forms. Methods ------- | writeValue() | | --- | | Writes a new value to the element. | | `writeValue(obj: any): void` Parameters | | | | | --- | --- | --- | | `obj` | `any` | The new value for the element | Returns `void` | | This method is called by the forms API to write to the view when programmatic changes from model to view are requested. | | Usage Notes Write a value to the element The following example writes a value to the native DOM element. ``` writeValue(value: any): void { this._renderer.setProperty(this._elementRef.nativeElement, 'value', value); } ``` | | registerOnChange() | | --- | | Registers a callback function that is called when the control's value changes in the UI. | | `registerOnChange(fn: any): void` Parameters | | | | | --- | --- | --- | | `fn` | `any` | The callback function to register | Returns `void` | | This method is called by the forms API on initialization to update the form model when values propagate from the view to the model. When implementing the `registerOnChange` method in your own value accessor, save the given function so your class calls it at the appropriate time. | | Usage Notes Store the change function The following example stores the provided function as an internal method. ``` registerOnChange(fn: (_: any) => void): void { this._onChange = fn; } ``` When the value changes in the UI, call the registered function to allow the forms API to update itself: ``` host: { '(change)': '_onChange($event.target.value)' } ``` | | registerOnTouched() | | --- | | Registers a callback function that is called by the forms API on initialization to update the form model on blur. | | `registerOnTouched(fn: any): void` Parameters | | | | | --- | --- | --- | | `fn` | `any` | The callback function to register | Returns `void` | | When implementing `registerOnTouched` in your own value accessor, save the given function so your class calls it when the control should be considered blurred or "touched". | | Usage Notes Store the callback function The following example stores the provided function as an internal method. ``` registerOnTouched(fn: any): void { this._onTouched = fn; } ``` On blur (or equivalent), your class should call the registered function to allow the forms API to update itself: ``` host: { '(blur)': '_onTouched()' } ``` | | setDisabledState() | | --- | | Function that is called by the forms API when the control status changes to or from 'DISABLED'. Depending on the status, it enables or disables the appropriate DOM element. | | `setDisabledState(isDisabled: boolean)?: void` Parameters | | | | | --- | --- | --- | | `isDisabled` | `boolean` | The disabled status to set on the element | Returns `void` | | Usage Notes The following is an example of writing the disabled property to a native DOM element: ``` setDisabledState(isDisabled: boolean): void { this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled); } ``` | angular NG_VALUE_ACCESSOR NG\_VALUE\_ACCESSOR =================== `const` Used to provide a `[ControlValueAccessor](controlvalueaccessor)` for form controls. [See more...](ng_value_accessor#description) ### `const NG_VALUE_ACCESSOR: InjectionToken<readonly ControlValueAccessor[]>;` #### Description See `[DefaultValueAccessor](defaultvalueaccessor)` for how to implement one. angular FormArrayName FormArrayName ============= `directive` Syncs a nested `[FormArray](formarray)` to a DOM element. [See more...](formarrayname#description) See also -------- * [Reactive Forms Guide](../../guide/reactive-forms) * `[AbstractControl](abstractcontrol)` Exported from ------------- * [``` ReactiveFormsModule ```](reactiveformsmodule) Selectors --------- * `[[formArrayName](formarrayname)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)('[formArrayName](formarrayname)')name: string | number | null` | Tracks the name of the `[FormArray](formarray)` bound to the directive. The name corresponds to a key in the parent `[FormGroup](formgroup)` or `[FormArray](formarray)`. Accepts a name as a string or a number. The name in the form of a string is useful for individual forms, while the numerical form allows for form arrays to be bound to indices when iterating over arrays in a `[FormArray](formarray)`. | | `control: [FormArray](formarray)` | Read-Only The `[FormArray](formarray)` bound to this directive. | | `formDirective: [FormGroupDirective](formgroupdirective) | null` | Read-Only The top-level directive for this group if present, otherwise null. | | `path: string[]` | Read-Only Returns an array that represents the path from the top-level form to this control. Each index is the string name of the control on that level. | ### Inherited from `[ControlContainer](controlcontainer)` * `[name: string | number | null](controlcontainer#name)` * `[formDirective: Form | null](controlcontainer#formDirective)` * `[path: string[] | null](controlcontainer#path)` ### Inherited from `[AbstractControlDirective](abstractcontroldirective)` * `[abstract control: AbstractControl | null](abstractcontroldirective#control)` * `[value: any](abstractcontroldirective#value)` * `[valid: boolean | null](abstractcontroldirective#valid)` * `[invalid: boolean | null](abstractcontroldirective#invalid)` * `[pending: boolean | null](abstractcontroldirective#pending)` * `[disabled: boolean | null](abstractcontroldirective#disabled)` * `[enabled: boolean | null](abstractcontroldirective#enabled)` * `[errors: ValidationErrors | null](abstractcontroldirective#errors)` * `[pristine: boolean | null](abstractcontroldirective#pristine)` * `[dirty: boolean | null](abstractcontroldirective#dirty)` * `[touched: boolean | null](abstractcontroldirective#touched)` * `[status: string | null](abstractcontroldirective#status)` * `[untouched: boolean | null](abstractcontroldirective#untouched)` * `[statusChanges: Observable<any> | null](abstractcontroldirective#statusChanges)` * `[valueChanges: Observable<any> | null](abstractcontroldirective#valueChanges)` * `[path: string[] | null](abstractcontroldirective#path)` * `[validator: ValidatorFn | null](abstractcontroldirective#validator)` * `[asyncValidator: AsyncValidatorFn | null](abstractcontroldirective#asyncValidator)` Description ----------- This directive is designed to be used with a parent `[FormGroupDirective](formgroupdirective)` (selector: `[formGroup]`). It accepts the string name of the nested `[FormArray](formarray)` you want to link, and will look for a `[FormArray](formarray)` registered with that name in the parent `[FormGroup](formgroup)` instance you passed into `[FormGroupDirective](formgroupdirective)`. ### Example ``` import {Component} from '@angular/core'; import {FormArray, FormControl, FormGroup} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form [formGroup]="form" (ngSubmit)="onSubmit()"> <div formArrayName="cities"> <div *ngFor="let city of cities.controls; index as i"> <input [formControlName]="i" placeholder="City"> </div> </div> <button>Submit</button> </form> <button (click)="addCity()">Add City</button> <button (click)="setPreset()">Set preset</button> `, }) export class NestedFormArray { form = new FormGroup({ cities: new FormArray([ new FormControl('SF'), new FormControl('NY'), ]), }); get cities(): FormArray { return this.form.get('cities') as FormArray; } addCity() { this.cities.push(new FormControl()); } onSubmit() { console.log(this.cities.value); // ['SF', 'NY'] console.log(this.form.value); // { cities: ['SF', 'NY'] } } setPreset() { this.cities.patchValue(['LA', 'MTV']); } } ``` ### Inherited from `[AbstractControlDirective](abstractcontroldirective)` * `[reset(value: any = undefined): void](abstractcontroldirective#reset)` * `[hasError(errorCode: string, path?: string | (string | number)[]): boolean](abstractcontroldirective#hasError)` * `[getError(errorCode: string, path?: string | (string | number)[]): any](abstractcontroldirective#getError)`
programming_docs
angular FormControlName FormControlName =============== `directive` Syncs a `[FormControl](formcontrol)` in an existing `[FormGroup](formgroup)` to a form control element by name. See also -------- * [Reactive Forms Guide](../../guide/reactive-forms) * `[FormControl](formcontrol)` * `[AbstractControl](abstractcontrol)` Exported from ------------- * [``` ReactiveFormsModule ```](reactiveformsmodule) Selectors --------- * `[[formControlName](formcontrolname)]` Properties ---------- | Property | Description | | --- | --- | | `control: [FormControl](formcontrol)` | Read-Only Tracks the `[FormControl](formcontrol)` instance bound to the directive. | | `@[Input](../core/input)('[formControlName](formcontrolname)')name: string | number | null` | Tracks the name of the `[FormControl](formcontrol)` bound to the directive. The name corresponds to a key in the parent `[FormGroup](formgroup)` or `[FormArray](formarray)`. Accepts a name as a string or a number. The name in the form of a string is useful for individual forms, while the numerical form allows for form controls to be bound to indices when iterating over controls in a `[FormArray](formarray)`. | | `@[Input](../core/input)('disabled')isDisabled: boolean` | Write-Only Triggers a warning in dev mode that this input should not be used with reactive forms. | | `@[Input](../core/input)('[ngModel](ngmodel)')model: any` | **Deprecated** as of v6 | | `@[Output](../core/output)('ngModelChange')update: [EventEmitter](../core/eventemitter)` | **Deprecated** as of v6 | | `path: string[]` | Read-Only Returns an array that represents the path from the top-level form to this control. Each index is the string name of the control on that level. | | `formDirective: any` | Read-Only The top-level directive for this group if present, otherwise null. | ### Inherited from `[NgControl](ngcontrol)` * `[name: string | number | null](ngcontrol#name)` * `[valueAccessor: ControlValueAccessor | null](ngcontrol#valueAccessor)` ### Inherited from `[AbstractControlDirective](abstractcontroldirective)` * `[abstract control: AbstractControl | null](abstractcontroldirective#control)` * `[value: any](abstractcontroldirective#value)` * `[valid: boolean | null](abstractcontroldirective#valid)` * `[invalid: boolean | null](abstractcontroldirective#invalid)` * `[pending: boolean | null](abstractcontroldirective#pending)` * `[disabled: boolean | null](abstractcontroldirective#disabled)` * `[enabled: boolean | null](abstractcontroldirective#enabled)` * `[errors: ValidationErrors | null](abstractcontroldirective#errors)` * `[pristine: boolean | null](abstractcontroldirective#pristine)` * `[dirty: boolean | null](abstractcontroldirective#dirty)` * `[touched: boolean | null](abstractcontroldirective#touched)` * `[status: string | null](abstractcontroldirective#status)` * `[untouched: boolean | null](abstractcontroldirective#untouched)` * `[statusChanges: Observable<any> | null](abstractcontroldirective#statusChanges)` * `[valueChanges: Observable<any> | null](abstractcontroldirective#valueChanges)` * `[path: string[] | null](abstractcontroldirective#path)` * `[validator: ValidatorFn | null](abstractcontroldirective#validator)` * `[asyncValidator: AsyncValidatorFn | null](abstractcontroldirective#asyncValidator)` Description ----------- ### Register `[FormControl](formcontrol)` within a group The following example shows how to register multiple form controls within a form group and set their value. ``` import {Component} from '@angular/core'; import {FormControl, FormGroup, Validators} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form [formGroup]="form" (ngSubmit)="onSubmit()"> <div *ngIf="first.invalid"> Name is too short. </div> <input formControlName="first" placeholder="First name"> <input formControlName="last" placeholder="Last name"> <button type="submit">Submit</button> </form> <button (click)="setValue()">Set preset value</button> `, }) export class SimpleFormGroup { form = new FormGroup({ first: new FormControl('Nancy', Validators.minLength(2)), last: new FormControl('Drew'), }); get first(): any { return this.form.get('first'); } onSubmit(): void { console.log(this.form.value); // {first: 'Nancy', last: 'Drew'} } setValue() { this.form.setValue({first: 'Carson', last: 'Drew'}); } } ``` To see `[formControlName](formcontrolname)` examples with different form control types, see: * Radio buttons: `[RadioControlValueAccessor](radiocontrolvalueaccessor)` * Selects: `[SelectControlValueAccessor](selectcontrolvalueaccessor)` ### Use with ngModel is deprecated Support for using the `[ngModel](ngmodel)` input property and `ngModelChange` event with reactive form directives has been deprecated in Angular v6 and is scheduled for removal in a future version of Angular. For details, see [Deprecated features](../../guide/deprecations#ngmodel-with-reactive-forms). Methods ------- | viewToModelUpdate() | | --- | | Sets the new value for the view model and emits an `ngModelChange` event. | | `viewToModelUpdate(newValue: any): void` Parameters | | | | | --- | --- | --- | | `newValue` | `any` | The new value for the view model. | Returns `void` | ### Inherited from `[NgControl](ngcontrol)` * `[abstract viewToModelUpdate(newValue: any): void](ngcontrol#viewToModelUpdate)` ### Inherited from `[AbstractControlDirective](abstractcontroldirective)` * `[reset(value: any = undefined): void](abstractcontroldirective#reset)` * `[hasError(errorCode: string, path?: string | (string | number)[]): boolean](abstractcontroldirective#hasError)` * `[getError(errorCode: string, path?: string | (string | number)[]): any](abstractcontroldirective#getError)` angular FormControlOptions FormControlOptions ================== `interface` Interface for options provided to a `[FormControl](formcontrol)`. [See more...](formcontroloptions#description) ``` interface FormControlOptions extends AbstractControlOptions { nonNullable?: boolean initialValueIsDefault?: boolean // inherited from forms/AbstractControlOptions validators?: ValidatorFn | ValidatorFn[] | null asyncValidators?: AsyncValidatorFn | AsyncValidatorFn[] | null updateOn?: 'change' | 'blur' | 'submit' } ``` Description ----------- This interface extends all options from [`AbstractControlOptions`](abstractcontroloptions), plus some options unique to `[FormControl](formcontrol)`. Properties ---------- | Property | Description | | --- | --- | | `nonNullable?: boolean` | Whether to use the initial value used to construct the `[FormControl](formcontrol)` as its default value as well. If this option is false or not provided, the default value of a FormControl is `null`. When a FormControl is reset without an explicit value, its value reverts to its default value. | | `initialValueIsDefault?: boolean` | **Deprecated** Use `nonNullable` instead. | angular NgModel NgModel ======= `directive` Creates a `[FormControl](formcontrol)` instance from a domain model and binds it to a form control element. [See more...](ngmodel#description) See also -------- * `[RadioControlValueAccessor](radiocontrolvalueaccessor)` * `[SelectControlValueAccessor](selectcontrolvalueaccessor)` Exported from ------------- * [``` FormsModule ```](formsmodule) Selectors --------- * `[[ngModel](ngmodel)]*:not([[formControlName](formcontrolname)])**:not([formControl])*` Properties ---------- | Property | Description | | --- | --- | | `control: [FormControl](formcontrol)` | Read-Only | | `@[Input](../core/input)()name: string` | Tracks the name bound to the directive. If a parent form exists, it uses this name as a key to retrieve this control's value. | | `@[Input](../core/input)('disabled')isDisabled: boolean` | Tracks whether the control is disabled. | | `@[Input](../core/input)('[ngModel](ngmodel)')model: any` | Tracks the value bound to this directive. | | `@[Input](../core/input)('ngModelOptions')options: { name?: string; standalone?: boolean; updateOn?: FormHooks; }` | Tracks the configuration options for this `[ngModel](ngmodel)` instance. **name**: An alternative to setting the name attribute on the form control element. See the [example](ngmodel#using-ngmodel-on-a-standalone-control) for using `[NgModel](ngmodel)` as a standalone control. **standalone**: When set to true, the `[ngModel](ngmodel)` will not register itself with its parent form, and acts as if it's not in the form. Defaults to false. If no parent form exists, this option has no effect. **updateOn**: Defines the event upon which the form control value and validity update. Defaults to 'change'. Possible values: `'change'` | `'blur'` | `'submit'`. | | `@[Output](../core/output)('ngModelChange')update: [EventEmitter](../core/eventemitter)` | Event emitter for producing the `ngModelChange` event after the view model updates. | | `path: string[]` | Read-Only Returns an array that represents the path from the top-level form to this control. Each index is the string name of the control on that level. | | `formDirective: any` | Read-Only The top-level directive for this control if present, otherwise null. | ### Inherited from `[NgControl](ngcontrol)` * `[name: string | number | null](ngcontrol#name)` * `[valueAccessor: ControlValueAccessor | null](ngcontrol#valueAccessor)` ### Inherited from `[AbstractControlDirective](abstractcontroldirective)` * `[abstract control: AbstractControl | null](abstractcontroldirective#control)` * `[value: any](abstractcontroldirective#value)` * `[valid: boolean | null](abstractcontroldirective#valid)` * `[invalid: boolean | null](abstractcontroldirective#invalid)` * `[pending: boolean | null](abstractcontroldirective#pending)` * `[disabled: boolean | null](abstractcontroldirective#disabled)` * `[enabled: boolean | null](abstractcontroldirective#enabled)` * `[errors: ValidationErrors | null](abstractcontroldirective#errors)` * `[pristine: boolean | null](abstractcontroldirective#pristine)` * `[dirty: boolean | null](abstractcontroldirective#dirty)` * `[touched: boolean | null](abstractcontroldirective#touched)` * `[status: string | null](abstractcontroldirective#status)` * `[untouched: boolean | null](abstractcontroldirective#untouched)` * `[statusChanges: Observable<any> | null](abstractcontroldirective#statusChanges)` * `[valueChanges: Observable<any> | null](abstractcontroldirective#valueChanges)` * `[path: string[] | null](abstractcontroldirective#path)` * `[validator: ValidatorFn | null](abstractcontroldirective#validator)` * `[asyncValidator: AsyncValidatorFn | null](abstractcontroldirective#asyncValidator)` Template variable references ---------------------------- | Identifier | Usage | | --- | --- | | `[ngModel](ngmodel)` | `#myTemplateVar="[ngModel](ngmodel)"` | Description ----------- The `[FormControl](formcontrol)` instance tracks the value, user interaction, and validation status of the control and keeps the view synced with the model. If used within a parent form, the directive also registers itself with the form as a child control. This directive is used by itself or as part of a larger form. Use the `[ngModel](ngmodel)` selector to activate it. It accepts a domain model as an optional `[Input](../core/input)`. If you have a one-way binding to `[ngModel](ngmodel)` with `[]` syntax, changing the domain model's value in the component class sets the value in the view. If you have a two-way binding with `[()]` syntax (also known as 'banana-in-a-box syntax'), the value in the UI always syncs back to the domain model in your class. To inspect the properties of the associated `[FormControl](formcontrol)` (like the validity state), export the directive into a local template variable using `[ngModel](ngmodel)` as the key (ex: `#myVar="[ngModel](ngmodel)"`). You can then access the control using the directive's `control` property. However, the most commonly used properties (like `valid` and `dirty`) also exist on the control for direct access. See a full list of properties directly available in `[AbstractControlDirective](abstractcontroldirective)`. ### Using ngModel on a standalone control The following examples show a simple standalone control using `[ngModel](ngmodel)`: ``` import {Component} from '@angular/core'; @Component({ selector: 'example-app', template: ` <input [(ngModel)]="name" #ctrl="ngModel" required> <p>Value: {{ name }}</p> <p>Valid: {{ ctrl.valid }}</p> <button (click)="setValue()">Set value</button> `, }) export class SimpleNgModelComp { name: string = ''; setValue() { this.name = 'Nancy'; } } ``` When using the `[ngModel](ngmodel)` within `<form>` tags, you'll also need to supply a `name` attribute so that the control can be registered with the parent form under that name. In the context of a parent form, it's often unnecessary to include one-way or two-way binding, as the parent form syncs the value for you. You access its properties by exporting it into a local template variable using `[ngForm](ngform)` such as (`#f="[ngForm](ngform)"`). Use the variable where needed on form submission. If you do need to populate initial values into your form, using a one-way binding for `[ngModel](ngmodel)` tends to be sufficient as long as you use the exported form's value rather than the domain model's value on submit. ### Using ngModel within a form The following example shows controls using `[ngModel](ngmodel)` within a form: ``` import {Component} from '@angular/core'; import {NgForm} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate> <input name="first" ngModel required #first="ngModel"> <input name="last" ngModel> <button>Submit</button> </form> <p>First name value: {{ first.value }}</p> <p>First name valid: {{ first.valid }}</p> <p>Form value: {{ f.value | json }}</p> <p>Form valid: {{ f.valid }}</p> `, }) export class SimpleFormComp { onSubmit(f: NgForm) { console.log(f.value); // { first: '', last: '' } console.log(f.valid); // false } } ``` ### Using a standalone ngModel within a group The following example shows you how to use a standalone ngModel control within a form. This controls the display of the form, but doesn't contain form data. ``` <form> <input name="login" ngModel placeholder="Login"> <input type="checkbox" ngModel [ngModelOptions]="{standalone: true}"> Show more options? </form> <!-- form value: {login: ''} --> ``` ### Setting the ngModel `name` attribute through options The following example shows you an alternate way to set the name attribute. Here, an attribute identified as name is used within a custom form control component. To still be able to specify the NgModel's name, you must specify it using the `ngModelOptions` input instead. ``` <form> <my-custom-form-control name="Nancy" ngModel [ngModelOptions]="{name: 'user'}"> </my-custom-form-control> </form> <!-- form value: {user: ''} --> ``` Methods ------- | viewToModelUpdate() | | --- | | Sets the new value for the view model and emits an `ngModelChange` event. | | `viewToModelUpdate(newValue: any): void` Parameters | | | | | --- | --- | --- | | `newValue` | `any` | The new value emitted by `ngModelChange`. | Returns `void` | ### Inherited from `[NgControl](ngcontrol)` * `[abstract viewToModelUpdate(newValue: any): void](ngcontrol#viewToModelUpdate)` ### Inherited from `[AbstractControlDirective](abstractcontroldirective)` * `[reset(value: any = undefined): void](abstractcontroldirective#reset)` * `[hasError(errorCode: string, path?: string | (string | number)[]): boolean](abstractcontroldirective#hasError)` * `[getError(errorCode: string, path?: string | (string | number)[]): any](abstractcontroldirective#getError)` angular Form Form ==== `interface` An interface implemented by `[FormGroupDirective](formgroupdirective)` and `[NgForm](ngform)` directives. [See more...](form#description) ``` interface Form { addControl(dir: NgControl): void removeControl(dir: NgControl): void getControl(dir: NgControl): FormControl addFormGroup(dir: AbstractFormGroupDirective): void removeFormGroup(dir: AbstractFormGroupDirective): void getFormGroup(dir: AbstractFormGroupDirective): FormGroup updateModel(dir: NgControl, value: any): void } ``` Class implementations --------------------- * `[NgForm](ngform)` * `[FormGroupDirective](formgroupdirective)` Description ----------- Only used by the `[ReactiveFormsModule](reactiveformsmodule)` and `[FormsModule](formsmodule)`. Methods ------- | addControl() | | --- | | Add a control to this form. | | `addControl(dir: NgControl): void` Parameters | | | | | --- | --- | --- | | `dir` | `[NgControl](ngcontrol)` | The control directive to add to the form. | Returns `void` | | removeControl() | | --- | | Remove a control from this form. | | `removeControl(dir: NgControl): void` Parameters | | | | | --- | --- | --- | | `dir` | `[NgControl](ngcontrol)` | | Returns `void` | | getControl() | | --- | | The control directive from which to get the `[FormControl](formcontrol)`. | | `getControl(dir: NgControl): FormControl` Parameters | | | | | --- | --- | --- | | `dir` | `[NgControl](ngcontrol)` | | Returns `[FormControl](formcontrol)` | | addFormGroup() | | --- | | Add a group of controls to this form. | | `addFormGroup(dir: AbstractFormGroupDirective): void` Parameters | | | | | --- | --- | --- | | `dir` | `[AbstractFormGroupDirective](abstractformgroupdirective)` | | Returns `void` | | removeFormGroup() | | --- | | Remove a group of controls to this form. | | `removeFormGroup(dir: AbstractFormGroupDirective): void` Parameters | | | | | --- | --- | --- | | `dir` | `[AbstractFormGroupDirective](abstractformgroupdirective)` | | Returns `void` | | getFormGroup() | | --- | | The `[FormGroup](formgroup)` associated with a particular `[AbstractFormGroupDirective](abstractformgroupdirective)`. | | `getFormGroup(dir: AbstractFormGroupDirective): FormGroup` Parameters | | | | | --- | --- | --- | | `dir` | `[AbstractFormGroupDirective](abstractformgroupdirective)` | | Returns `[FormGroup](formgroup)` | | updateModel() | | --- | | Update the model for a particular control with a new value. | | `updateModel(dir: NgControl, value: any): void` Parameters | | | | | --- | --- | --- | | `dir` | `[NgControl](ngcontrol)` | | | `value` | `any` | | Returns `void` | angular AbstractControl AbstractControl =============== `class` This is the base class for `[FormControl](formcontrol)`, `[FormGroup](formgroup)`, and `[FormArray](formarray)`. [See more...](abstractcontrol#description) ``` abstract class AbstractControl<TValue = any, TRawValue extends TValue = TValue> { constructor(validators: ValidatorFn | ValidatorFn[], asyncValidators: AsyncValidatorFn | AsyncValidatorFn[]) value: TValue validator: ValidatorFn | null asyncValidator: AsyncValidatorFn | null parent: FormGroup | FormArray | null status: FormControlStatus valid: boolean invalid: boolean pending: boolean disabled: boolean enabled: boolean errors: ValidationErrors | null pristine: boolean dirty: boolean touched: boolean untouched: boolean valueChanges: Observable<TValue> statusChanges: Observable<FormControlStatus> updateOn: FormHooks root: AbstractControl setValidators(validators: ValidatorFn | ValidatorFn[]): void setAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void addValidators(validators: ValidatorFn | ValidatorFn[]): void addAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void removeValidators(validators: ValidatorFn | ValidatorFn[]): void removeAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void hasValidator(validator: ValidatorFn): boolean hasAsyncValidator(validator: AsyncValidatorFn): boolean clearValidators(): void clearAsyncValidators(): void markAsTouched(opts: { onlySelf?: boolean; } = {}): void markAllAsTouched(): void markAsUntouched(opts: { onlySelf?: boolean; } = {}): void markAsDirty(opts: { onlySelf?: boolean; } = {}): void markAsPristine(opts: { onlySelf?: boolean; } = {}): void markAsPending(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void disable(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void enable(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void setParent(parent: FormGroup<any> | FormArray<any>): void abstract setValue(value: TRawValue, options?: Object): void abstract patchValue(value: TValue, options?: Object): void abstract reset(value?: TValue, options?: Object): void getRawValue(): any updateValueAndValidity(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void setErrors(errors: ValidationErrors, opts: { emitEvent?: boolean; } = {}): void get<P extends string | ((string | number)[])>(path: P): AbstractControl<ɵGetProperty<TRawValue, P>> | null getError(errorCode: string, path?: string | (string | number)[]): any hasError(errorCode: string, path?: string | (string | number)[]): boolean } ``` Subclasses ---------- * `[FormArray](formarray)` * `[FormGroup](formgroup)` + `[FormRecord](formrecord)` See also -------- * [Forms Guide](../../guide/forms) * [Reactive Forms Guide](../../guide/reactive-forms) * [Dynamic Forms Guide](../../guide/dynamic-form) Description ----------- It provides some of the shared behavior that all controls and groups of controls have, like running validators, calculating status, and resetting state. It also defines the properties that are shared between all sub-classes, like `value`, `valid`, and `dirty`. It shouldn't be instantiated directly. The first type parameter TValue represents the value type of the control (`control.value`). The optional type parameter TRawValue represents the raw value type (`control.getRawValue()`). Constructor ----------- | | | --- | | Initialize the AbstractControl instance. | | `constructor(validators: ValidatorFn | ValidatorFn[], asyncValidators: AsyncValidatorFn | AsyncValidatorFn[])` Parameters | | | | | --- | --- | --- | | `validators` | `[ValidatorFn](validatorfn) | [ValidatorFn](validatorfn)[]` | The function or array of functions that is used to determine the validity of this control synchronously. | | `asyncValidators` | `[AsyncValidatorFn](asyncvalidatorfn) | [AsyncValidatorFn](asyncvalidatorfn)[]` | The function or array of functions that is used to determine validity of this control asynchronously. | | Properties ---------- | Property | Description | | --- | --- | | `value: TValue` | Read-Only The current value of the control.* For a `[FormControl](formcontrol)`, the current value. * For an enabled `[FormGroup](formgroup)`, the values of enabled controls as an object with a key-value pair for each member of the group. * For a disabled `[FormGroup](formgroup)`, the values of all controls as an object with a key-value pair for each member of the group. * For a `[FormArray](formarray)`, the values of enabled controls as an array. | | `validator: [ValidatorFn](validatorfn) | null` | Returns the function that is used to determine the validity of this control synchronously. If multiple validators have been added, this will be a single composed function. See `[Validators.compose()](validators#compose)` for additional information. | | `asyncValidator: [AsyncValidatorFn](asyncvalidatorfn) | null` | Returns the function that is used to determine the validity of this control asynchronously. If multiple validators have been added, this will be a single composed function. See `[Validators.compose()](validators#compose)` for additional information. | | `parent: [FormGroup](formgroup) | [FormArray](formarray) | null` | Read-Only The parent control. | | `status: [FormControlStatus](formcontrolstatus)` | Read-Only The validation status of the control. See also:* `[FormControlStatus](formcontrolstatus)` These status values are mutually exclusive, so a control cannot be both valid AND invalid or invalid AND disabled. | | `valid: boolean` | Read-Only A control is `valid` when its `status` is `VALID`. See also:* [`status`](abstractcontrol#status) | | `invalid: boolean` | Read-Only A control is `invalid` when its `status` is `INVALID`. See also:* [`status`](abstractcontrol#status) | | `pending: boolean` | Read-Only A control is `pending` when its `status` is `PENDING`. See also:* [`status`](abstractcontrol#status) | | `disabled: boolean` | Read-Only A control is `disabled` when its `status` is `DISABLED`. Disabled controls are exempt from validation checks and are not included in the aggregate value of their ancestor controls. See also:* [`status`](abstractcontrol#status) | | `enabled: boolean` | Read-Only A control is `enabled` as long as its `status` is not `DISABLED`. See also:* [`status`](abstractcontrol#status) | | `errors: [ValidationErrors](validationerrors) | null` | Read-Only An object containing any errors generated by failing validation, or null if there are no errors. | | `pristine: boolean` | Read-Only A control is `pristine` if the user has not yet changed the value in the UI. | | `dirty: boolean` | Read-Only A control is `dirty` if the user has changed the value in the UI. | | `touched: boolean` | Read-Only True if the control is marked as `touched`. A control is marked `touched` once the user has triggered a `blur` event on it. | | `untouched: boolean` | Read-Only True if the control has not been marked as touched A control is `untouched` if the user has not yet triggered a `blur` event on it. | | `valueChanges: Observable<TValue>` | Read-Only A multicasting observable that emits an event every time the value of the control changes, in the UI or programmatically. It also emits an event each time you call enable() or disable() without passing along {emitEvent: false} as a function argument. | | `statusChanges: Observable<[FormControlStatus](formcontrolstatus)>` | Read-Only A multicasting observable that emits an event every time the validation `status` of the control recalculates. See also:* `[FormControlStatus](formcontrolstatus)` * [`status`](abstractcontrol#status) | | `updateOn: FormHooks` | Read-Only Reports the update strategy of the `[AbstractControl](abstractcontrol)` (meaning the event on which the control updates itself). Possible values: `'change'` | `'blur'` | `'submit'` Default value: `'change'` | | `root: [AbstractControl](abstractcontrol)` | Read-Only Retrieves the top-level ancestor of this control. | Methods ------- | setValidators() | | --- | | Sets the synchronous validators that are active on this control. Calling this overwrites any existing synchronous validators. | | `setValidators(validators: ValidatorFn | ValidatorFn[]): void` Parameters | | | | | --- | --- | --- | | `validators` | `[ValidatorFn](validatorfn) | [ValidatorFn](validatorfn)[]` | | Returns `void` | | When you add or remove a validator at run time, you must call `updateValueAndValidity()` for the new validation to take effect. If you want to add a new validator without affecting existing ones, consider using `addValidators()` method instead. | | setAsyncValidators() | | --- | | Sets the asynchronous validators that are active on this control. Calling this overwrites any existing asynchronous validators. | | `setAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void` Parameters | | | | | --- | --- | --- | | `validators` | `[AsyncValidatorFn](asyncvalidatorfn) | [AsyncValidatorFn](asyncvalidatorfn)[]` | | Returns `void` | | When you add or remove a validator at run time, you must call `updateValueAndValidity()` for the new validation to take effect. If you want to add a new validator without affecting existing ones, consider using `addAsyncValidators()` method instead. | | addValidators() | | --- | | Add a synchronous validator or validators to this control, without affecting other validators. | | `addValidators(validators: ValidatorFn | ValidatorFn[]): void` Parameters | | | | | --- | --- | --- | | `validators` | `[ValidatorFn](validatorfn) | [ValidatorFn](validatorfn)[]` | The new validator function or functions to add to this control. | Returns `void` | | When you add or remove a validator at run time, you must call `updateValueAndValidity()` for the new validation to take effect. Adding a validator that already exists will have no effect. If duplicate validator functions are present in the `validators` array, only the first instance would be added to a form control. | | addAsyncValidators() | | --- | | Add an asynchronous validator or validators to this control, without affecting other validators. | | `addAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void` Parameters | | | | | --- | --- | --- | | `validators` | `[AsyncValidatorFn](asyncvalidatorfn) | [AsyncValidatorFn](asyncvalidatorfn)[]` | The new asynchronous validator function or functions to add to this control. | Returns `void` | | When you add or remove a validator at run time, you must call `updateValueAndValidity()` for the new validation to take effect. Adding a validator that already exists will have no effect. | | removeValidators() | | --- | | Remove a synchronous validator from this control, without affecting other validators. Validators are compared by function reference; you must pass a reference to the exact same validator function as the one that was originally set. If a provided validator is not found, it is ignored. | | `removeValidators(validators: ValidatorFn | ValidatorFn[]): void` Parameters | | | | | --- | --- | --- | | `validators` | `[ValidatorFn](validatorfn) | [ValidatorFn](validatorfn)[]` | The validator or validators to remove. | Returns `void` | | Usage Notes Reference to a ValidatorFn ``` // Reference to the RequiredValidator const ctrl = new FormControl<string | null>('', Validators.required); ctrl.removeValidators(Validators.required); // Reference to anonymous function inside MinValidator const minValidator = Validators.min(3); const ctrl = new FormControl<string | null>('', minValidator); expect(ctrl.hasValidator(minValidator)).toEqual(true) expect(ctrl.hasValidator(Validators.min(3))).toEqual(false) ctrl.removeValidators(minValidator); ``` When you add or remove a validator at run time, you must call `updateValueAndValidity()` for the new validation to take effect. | | removeAsyncValidators() | | --- | | Remove an asynchronous validator from this control, without affecting other validators. Validators are compared by function reference; you must pass a reference to the exact same validator function as the one that was originally set. If a provided validator is not found, it is ignored. | | `removeAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void` Parameters | | | | | --- | --- | --- | | `validators` | `[AsyncValidatorFn](asyncvalidatorfn) | [AsyncValidatorFn](asyncvalidatorfn)[]` | The asynchronous validator or validators to remove. | Returns `void` | | When you add or remove a validator at run time, you must call `updateValueAndValidity()` for the new validation to take effect. | | hasValidator() | | --- | | Check whether a synchronous validator function is present on this control. The provided validator must be a reference to the exact same function that was provided. | | `hasValidator(validator: ValidatorFn): boolean` Parameters | | | | | --- | --- | --- | | `validator` | `[ValidatorFn](validatorfn)` | The validator to check for presence. Compared by function reference. | Returns `boolean`: Whether the provided validator was found on this control. | | Usage Notes Reference to a ValidatorFn ``` // Reference to the RequiredValidator const ctrl = new FormControl<number | null>(0, Validators.required); expect(ctrl.hasValidator(Validators.required)).toEqual(true) // Reference to anonymous function inside MinValidator const minValidator = Validators.min(3); const ctrl = new FormControl<number | null>(0, minValidator); expect(ctrl.hasValidator(minValidator)).toEqual(true) expect(ctrl.hasValidator(Validators.min(3))).toEqual(false) ``` | | hasAsyncValidator() | | --- | | Check whether an asynchronous validator function is present on this control. The provided validator must be a reference to the exact same function that was provided. | | `hasAsyncValidator(validator: AsyncValidatorFn): boolean` Parameters | | | | | --- | --- | --- | | `validator` | `[AsyncValidatorFn](asyncvalidatorfn)` | The asynchronous validator to check for presence. Compared by function reference. | Returns `boolean`: Whether the provided asynchronous validator was found on this control. | | clearValidators() | | --- | | Empties out the synchronous validator list. | | `clearValidators(): void` Parameters There are no parameters. Returns `void` | | When you add or remove a validator at run time, you must call `updateValueAndValidity()` for the new validation to take effect. | | clearAsyncValidators() | | --- | | Empties out the async validator list. | | `clearAsyncValidators(): void` Parameters There are no parameters. Returns `void` | | When you add or remove a validator at run time, you must call `updateValueAndValidity()` for the new validation to take effect. | | markAsTouched() | | --- | | Marks the control as `touched`. A control is touched by focus and blur events that do not change the value. See also:* `markAsUntouched()` * `markAsDirty()` * `markAsPristine()` | | `markAsTouched(opts: { onlySelf?: boolean; } = {}): void` Parameters | | | | | --- | --- | --- | | `opts` | `object` | Configuration options that determine how the control propagates changes and emits events after marking is applied.* `onlySelf`: When true, mark only this control. When false or not supplied, marks all direct ancestors. Default is false. Optional. Default is `{}`. | Returns `void` | | markAllAsTouched() | | --- | | Marks the control and all its descendant controls as `touched`. See also:* `markAsTouched()` | | `markAllAsTouched(): void` Parameters There are no parameters. Returns `void` | | markAsUntouched() | | --- | | Marks the control as `untouched`. See also:* `markAsTouched()` * `markAsDirty()` * `markAsPristine()` | | `markAsUntouched(opts: { onlySelf?: boolean; } = {}): void` Parameters | | | | | --- | --- | --- | | `opts` | `object` | Configuration options that determine how the control propagates changes and emits events after the marking is applied.* `onlySelf`: When true, mark only this control. When false or not supplied, marks all direct ancestors. Default is false. Optional. Default is `{}`. | Returns `void` | | If the control has any children, also marks all children as `untouched` and recalculates the `touched` status of all parent controls. | | markAsDirty() | | --- | | Marks the control as `dirty`. A control becomes dirty when the control's value is changed through the UI; compare `markAsTouched`. See also:* `markAsTouched()` * `markAsUntouched()` * `markAsPristine()` | | `markAsDirty(opts: { onlySelf?: boolean; } = {}): void` Parameters | | | | | --- | --- | --- | | `opts` | `object` | Configuration options that determine how the control propagates changes and emits events after marking is applied.* `onlySelf`: When true, mark only this control. When false or not supplied, marks all direct ancestors. Default is false. Optional. Default is `{}`. | Returns `void` | | markAsPristine() | | --- | | Marks the control as `pristine`. See also:* `markAsTouched()` * `markAsUntouched()` * `markAsDirty()` | | `markAsPristine(opts: { onlySelf?: boolean; } = {}): void` Parameters | | | | | --- | --- | --- | | `opts` | `object` | Configuration options that determine how the control emits events after marking is applied.* `onlySelf`: When true, mark only this control. When false or not supplied, marks all direct ancestors. Default is false. Optional. Default is `{}`. | Returns `void` | | If the control has any children, marks all children as `pristine`, and recalculates the `pristine` status of all parent controls. | | markAsPending() | | --- | | Marks the control as `pending`. See also:* [`status`](abstractcontrol#status) | | `markAsPending(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void` Parameters | | | | | --- | --- | --- | | `opts` | `object` | Configuration options that determine how the control propagates changes and emits events after marking is applied.* `onlySelf`: When true, mark only this control. When false or not supplied, marks all direct ancestors. Default is false. * `emitEvent`: When true or not supplied (the default), the `statusChanges` observable emits an event with the latest status the control is marked pending. When false, no events are emitted. Optional. Default is `{}`. | Returns `void` | | A control is pending while the control performs async validation. | | disable() | | --- | | Disables the control. This means the control is exempt from validation checks and excluded from the aggregate value of any parent. Its status is `DISABLED`. See also:* [`status`](abstractcontrol#status) | | `disable(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void` Parameters | | | | | --- | --- | --- | | `opts` | `object` | Configuration options that determine how the control propagates changes and emits events after the control is disabled.* `onlySelf`: When true, mark only this control. When false or not supplied, marks all direct ancestors. Default is false. * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and `valueChanges` observables emit events with the latest status and value when the control is disabled. When false, no events are emitted. Optional. Default is `{}`. | Returns `void` | | If the control has children, all children are also disabled. | | enable() | | --- | | Enables the control. This means the control is included in validation checks and the aggregate value of its parent. Its status recalculates based on its value and its validators. See also:* [`status`](abstractcontrol#status) | | `enable(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void` Parameters | | | | | --- | --- | --- | | `opts` | `object` | Configure options that control how the control propagates changes and emits events when marked as untouched* `onlySelf`: When true, mark only this control. When false or not supplied, marks all direct ancestors. Default is false. * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and `valueChanges` observables emit events with the latest status and value when the control is enabled. When false, no events are emitted. Optional. Default is `{}`. | Returns `void` | | By default, if the control has children, all children are enabled. | | setParent() | | --- | | Sets the parent of the control | | `setParent(parent: FormGroup<any> | FormArray<any>): void` Parameters | | | | | --- | --- | --- | | `parent` | `[FormGroup](formgroup)<any> | [FormArray](formarray)<any>` | The new parent. | Returns `void` | | setValue() | | --- | | Sets the value of the control. Abstract method (implemented in sub-classes). | | `abstract setValue(value: TRawValue, options?: Object): void` Parameters | | | | | --- | --- | --- | | `value` | `TRawValue` | | | `options` | `Object` | Optional. Default is `undefined`. | Returns `void` | | patchValue() | | --- | | Patches the value of the control. Abstract method (implemented in sub-classes). | | `abstract patchValue(value: TValue, options?: Object): void` Parameters | | | | | --- | --- | --- | | `value` | `TValue` | | | `options` | `Object` | Optional. Default is `undefined`. | Returns `void` | | reset() | | --- | | Resets the control. Abstract method (implemented in sub-classes). | | `abstract reset(value?: TValue, options?: Object): void` Parameters | | | | | --- | --- | --- | | `value` | `TValue` | Optional. Default is `undefined`. | | `options` | `Object` | Optional. Default is `undefined`. | Returns `void` | | getRawValue() | | --- | | The raw value of this control. For most control implementations, the raw value will include disabled children. | | `getRawValue(): any` Parameters There are no parameters. Returns `any` | | updateValueAndValidity() | | --- | | Recalculates the value and validation status of the control. | | `updateValueAndValidity(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void` Parameters | | | | | --- | --- | --- | | `opts` | `object` | Configuration options determine how the control propagates changes and emits events after updates and validity checks are applied.* `onlySelf`: When true, only update this control. When false or not supplied, update all direct ancestors. Default is false. * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and `valueChanges` observables emit events with the latest status and value when the control is updated. When false, no events are emitted. Optional. Default is `{}`. | Returns `void` | | By default, it also updates the value and validity of its ancestors. | | setErrors() | | --- | | Sets errors on a form control when running validations manually, rather than automatically. | | `setErrors(errors: ValidationErrors, opts: { emitEvent?: boolean; } = {}): void` Parameters | | | | | --- | --- | --- | | `errors` | `[ValidationErrors](validationerrors)` | | | `opts` | `object` | Configuration options that determine how the control propagates changes and emits events after the control errors are set.* `emitEvent`: When true or not supplied (the default), the `statusChanges` observable emits an event after the errors are set. Optional. Default is `{}`. | Returns `void` | | Calling `setErrors` also updates the validity of the parent control. | | Usage Notes Manually set the errors for a control ``` const login = new FormControl('someLogin'); login.setErrors({ notUnique: true }); expect(login.valid).toEqual(false); expect(login.errors).toEqual({ notUnique: true }); login.setValue('someOtherLogin'); expect(login.valid).toEqual(true); ``` | | get() | | --- | | Retrieves a child control given the control's name or path. | | `get<P extends string | (readonly (string | number)[])>(path: P): AbstractControl<ɵGetProperty<TRawValue, P>> | null` Parameters | | | | | --- | --- | --- | | `path` | `P` | | Returns `[AbstractControl](abstractcontrol)<ɵGetProperty<TRawValue, P>> | null` | | `get<P extends string | Array<string | number>>(path: P): AbstractControl<ɵGetProperty<TRawValue, P>> | null` Parameters | | | | | --- | --- | --- | | `path` | `P` | | Returns `[AbstractControl](abstractcontrol)<ɵGetProperty<TRawValue, P>> | null` This signature for `get` supports non-const (mutable) arrays. Inferred type information will not be as robust, so prefer to pass a `readonly` array if possible. | | This signature for get supports strings and `const` arrays (`.get(['foo', 'bar'] as const)`). | | Usage Notes Retrieve a nested control For example, to get a `name` control nested within a `person` sub-group:* `this.form.get('person.name');` -OR-* `this.form.get(['person', 'name'] as const);` // `as const` gives improved typings Retrieve a control in a FormArray When accessing an element inside a FormArray, you can use an element index. For example, to get a `price` control from the first element in an `items` array you can use:* `this.form.get('items.0.price');` -OR-* `this.form.get(['items', 0, 'price']);` | | getError() | | --- | | Reports error data for the control with the given path. | | `getError(errorCode: string, path?: string | (string | number)[]): any` Parameters | | | | | --- | --- | --- | | `errorCode` | `string` | The code of the error to check | | `path` | `string | (string | number)[]` | A list of control names that designates how to move from the current control to the control that should be queried for errors. Optional. Default is `undefined`. | Returns `any`: error data for that particular error. If the control or error is not present, null is returned. | | Usage Notes For example, for the following `[FormGroup](formgroup)`: ``` form = new FormGroup({ address: new FormGroup({ street: new FormControl() }) }); ``` The path to the 'street' control from the root form would be 'address' -> 'street'. It can be provided to this method in one of two formats:1. An array of string control names, e.g. `['address', 'street']` 2. A period-delimited list of control names in one string, e.g. `'address.street'` | | hasError() | | --- | | Reports whether the control with the given path has the error specified. | | `hasError(errorCode: string, path?: string | (string | number)[]): boolean` Parameters | | | | | --- | --- | --- | | `errorCode` | `string` | The code of the error to check | | `path` | `string | (string | number)[]` | A list of control names that designates how to move from the current control to the control that should be queried for errors. Optional. Default is `undefined`. | Returns `boolean`: whether the given error is present in the control at the given path. If the control is not present, false is returned. | | Usage Notes For example, for the following `[FormGroup](formgroup)`: ``` form = new FormGroup({ address: new FormGroup({ street: new FormControl() }) }); ``` The path to the 'street' control from the root form would be 'address' -> 'street'. It can be provided to this method in one of two formats:1. An array of string control names, e.g. `['address', 'street']` 2. A period-delimited list of control names in one string, e.g. `'address.street'` If no path is given, this method checks for the error on the current control. |
programming_docs
angular NgControlStatus NgControlStatus =============== `directive` Directive automatically applied to Angular form controls that sets CSS classes based on control status. Exported from ------------- * [``` ReactiveFormsModule ```](reactiveformsmodule) * [``` FormsModule ```](formsmodule) Selectors --------- * `[[formControlName](formcontrolname)]` * `[[ngModel](ngmodel)]` * `[formControl]` Description ----------- ### CSS classes applied The following classes are applied as the properties become true: * ng-valid * ng-invalid * ng-pending * ng-pristine * ng-dirty * ng-untouched * ng-touched angular MinLengthValidator MinLengthValidator ================== `directive` A directive that adds minimum length validation to controls marked with the `[minlength](minlengthvalidator)` attribute. The directive is provided with the `[NG\_VALIDATORS](ng_validators)` multi-provider list. See also -------- * [Form Validation](../../guide/form-validation) Exported from ------------- * [``` ReactiveFormsModule ```](reactiveformsmodule) * [``` FormsModule ```](formsmodule) Selectors --------- * `[[minlength](minlengthvalidator)][[formControlName](formcontrolname)]` * `[[minlength](minlengthvalidator)][formControl]` * `[[minlength](minlengthvalidator)][[ngModel](ngmodel)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)()[minlength](minlengthvalidator): string | number | null` | Tracks changes to the minimum length bound to this directive. | Description ----------- ### Adding a minimum length validator The following example shows how to add a minimum length validator to an input attached to an ngModel binding. ``` <input name="firstName" ngModel minlength="4"> ``` angular FormGroupName FormGroupName ============= `directive` Syncs a nested `[FormGroup](formgroup)` or `[FormRecord](formrecord)` to a DOM element. [See more...](formgroupname#description) See also -------- * [Reactive Forms Guide](../../guide/reactive-forms) Exported from ------------- * [``` ReactiveFormsModule ```](reactiveformsmodule) Selectors --------- * `[[formGroupName](formgroupname)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)('[formGroupName](formgroupname)')name: string | number | null` | Tracks the name of the `[FormGroup](formgroup)` bound to the directive. The name corresponds to a key in the parent `[FormGroup](formgroup)` or `[FormArray](formarray)`. Accepts a name as a string or a number. The name in the form of a string is useful for individual forms, while the numerical form allows for form groups to be bound to indices when iterating over groups in a `[FormArray](formarray)`. | ### Inherited from `[AbstractFormGroupDirective](abstractformgroupdirective)` * `[control: FormGroup](abstractformgroupdirective#control)` * `[path: string[]](abstractformgroupdirective#path)` * `[formDirective: Form | null](abstractformgroupdirective#formDirective)` ### Inherited from `[ControlContainer](controlcontainer)` * `[name: string | number | null](controlcontainer#name)` * `[formDirective: Form | null](controlcontainer#formDirective)` * `[path: string[] | null](controlcontainer#path)` ### Inherited from `[AbstractControlDirective](abstractcontroldirective)` * `[abstract control: AbstractControl | null](abstractcontroldirective#control)` * `[value: any](abstractcontroldirective#value)` * `[valid: boolean | null](abstractcontroldirective#valid)` * `[invalid: boolean | null](abstractcontroldirective#invalid)` * `[pending: boolean | null](abstractcontroldirective#pending)` * `[disabled: boolean | null](abstractcontroldirective#disabled)` * `[enabled: boolean | null](abstractcontroldirective#enabled)` * `[errors: ValidationErrors | null](abstractcontroldirective#errors)` * `[pristine: boolean | null](abstractcontroldirective#pristine)` * `[dirty: boolean | null](abstractcontroldirective#dirty)` * `[touched: boolean | null](abstractcontroldirective#touched)` * `[status: string | null](abstractcontroldirective#status)` * `[untouched: boolean | null](abstractcontroldirective#untouched)` * `[statusChanges: Observable<any> | null](abstractcontroldirective#statusChanges)` * `[valueChanges: Observable<any> | null](abstractcontroldirective#valueChanges)` * `[path: string[] | null](abstractcontroldirective#path)` * `[validator: ValidatorFn | null](abstractcontroldirective#validator)` * `[asyncValidator: AsyncValidatorFn | null](abstractcontroldirective#asyncValidator)` Description ----------- This directive can only be used with a parent `[FormGroupDirective](formgroupdirective)`. It accepts the string name of the nested `[FormGroup](formgroup)` or `[FormRecord](formrecord)` to link, and looks for a `[FormGroup](formgroup)` or `[FormRecord](formrecord)` registered with that name in the parent `[FormGroup](formgroup)` instance you passed into `[FormGroupDirective](formgroupdirective)`. Use nested form groups to validate a sub-group of a form separately from the rest or to group the values of certain controls into their own nested object. ### Access the group by name The following example uses the `AbstractControl.get` method to access the associated `[FormGroup](formgroup)` ``` this.form.get('name'); ``` ### Access individual controls in the group The following example uses the `AbstractControl.get` method to access individual controls within the group using dot syntax. ``` this.form.get('name.first'); ``` ### Register a nested `[FormGroup](formgroup)`. The following example registers a nested *name* `[FormGroup](formgroup)` within an existing `[FormGroup](formgroup)`, and provides methods to retrieve the nested `[FormGroup](formgroup)` and individual controls. ``` import {Component} from '@angular/core'; import {FormControl, FormGroup, Validators} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form [formGroup]="form" (ngSubmit)="onSubmit()"> <p *ngIf="name.invalid">Name is invalid.</p> <div formGroupName="name"> <input formControlName="first" placeholder="First name"> <input formControlName="last" placeholder="Last name"> </div> <input formControlName="email" placeholder="Email"> <button type="submit">Submit</button> </form> <button (click)="setPreset()">Set preset</button> `, }) export class NestedFormGroupComp { form = new FormGroup({ name: new FormGroup({ first: new FormControl('Nancy', Validators.minLength(2)), last: new FormControl('Drew', Validators.required) }), email: new FormControl() }); get first(): any { return this.form.get('name.first'); } get name(): any { return this.form.get('name'); } onSubmit() { console.log(this.first.value); // 'Nancy' console.log(this.name.value); // {first: 'Nancy', last: 'Drew'} console.log(this.form.value); // {name: {first: 'Nancy', last: 'Drew'}, email: ''} console.log(this.form.status); // VALID } setPreset() { this.name.setValue({first: 'Bess', last: 'Marvin'}); } } ``` ### Inherited from `[AbstractControlDirective](abstractcontroldirective)` * `[reset(value: any = undefined): void](abstractcontroldirective#reset)` * `[hasError(errorCode: string, path?: string | (string | number)[]): boolean](abstractcontroldirective#hasError)` * `[getError(errorCode: string, path?: string | (string | number)[]): any](abstractcontroldirective#getError)` angular FormsModule FormsModule =========== `ngmodule` Exports the required providers and directives for template-driven forms, making them available for import by NgModules that import this module. [See more...](formsmodule#description) ``` class FormsModule { static withConfig(opts: { callSetDisabledState?: SetDisabledStateOption; }): ModuleWithProviders<FormsModule> } ``` See also -------- * [Forms Overview](../../guide/forms-overview) * [Template-driven Forms Guide](../../guide/forms) Description ----------- Providers associated with this module: * `RadioControlRegistry` Static methods -------------- | withConfig() | | --- | | Provides options for configuring the forms module. | | `static withConfig(opts: { callSetDisabledState?: SetDisabledStateOption; }): ModuleWithProviders<FormsModule>` Parameters | | | | | --- | --- | --- | | `opts` | `object` | An object of configuration options* `callSetDisabledState` Configures whether to `always` call `setDisabledState`, which is more correct, or to only call it `whenDisabled`, which is the legacy behavior. | Returns `[ModuleWithProviders](../core/modulewithproviders)<[FormsModule](formsmodule)>` | Directives ---------- | Name | Description | | --- | --- | | [``` CheckboxControlValueAccessor ```](checkboxcontrolvalueaccessor) | A `[ControlValueAccessor](controlvalueaccessor)` for writing a value and listening to changes on a checkbox input element. | | [``` CheckboxRequiredValidator ```](checkboxrequiredvalidator) | A Directive that adds the `required` validator to checkbox controls marked with the `required` attribute. The directive is provided with the `[NG\_VALIDATORS](ng_validators)` multi-provider list. | | [``` DefaultValueAccessor ```](defaultvalueaccessor) | The default `[ControlValueAccessor](controlvalueaccessor)` for writing a value and listening to changes on input elements. The accessor is used by the `[FormControlDirective](formcontroldirective)`, `[FormControlName](formcontrolname)`, and `[NgModel](ngmodel)` directives. | | [``` EmailValidator ```](emailvalidator) | A directive that adds the `[email](emailvalidator)` validator to controls marked with the `[email](emailvalidator)` attribute. The directive is provided with the `[NG\_VALIDATORS](ng_validators)` multi-provider list. | | [``` MaxLengthValidator ```](maxlengthvalidator) | A directive that adds max length validation to controls marked with the `[maxlength](maxlengthvalidator)` attribute. The directive is provided with the `[NG\_VALIDATORS](ng_validators)` multi-provider list. | | [``` MaxValidator ```](maxvalidator) | A directive which installs the [`MaxValidator`](maxvalidator) for any `[formControlName](formcontrolname)`, `formControl`, or control with `[ngModel](ngmodel)` that also has a `[max](maxvalidator)` attribute. | | [``` MinLengthValidator ```](minlengthvalidator) | A directive that adds minimum length validation to controls marked with the `[minlength](minlengthvalidator)` attribute. The directive is provided with the `[NG\_VALIDATORS](ng_validators)` multi-provider list. | | [``` MinValidator ```](minvalidator) | A directive which installs the [`MinValidator`](minvalidator) for any `[formControlName](formcontrolname)`, `formControl`, or control with `[ngModel](ngmodel)` that also has a `[min](minvalidator)` attribute. | | [``` NgControlStatus ```](ngcontrolstatus) | Directive automatically applied to Angular form controls that sets CSS classes based on control status. | | [``` NgControlStatusGroup ```](ngcontrolstatusgroup) | Directive automatically applied to Angular form groups that sets CSS classes based on control status (valid/invalid/dirty/etc). On groups, this includes the additional class ng-submitted. | | [``` NgForm ```](ngform) | Creates a top-level `[FormGroup](formgroup)` instance and binds it to a form to track aggregate form value and validation status. | | [``` NgModel ```](ngmodel) | Creates a `[FormControl](formcontrol)` instance from a domain model and binds it to a form control element. | | [``` NgModelGroup ```](ngmodelgroup) | Creates and binds a `[FormGroup](formgroup)` instance to a DOM element. | | [``` NgSelectOption ```](ngselectoption) | Marks `<option>` as dynamic, so Angular can be notified when options change. | | [``` NumberValueAccessor ```](numbervalueaccessor) | The `[ControlValueAccessor](controlvalueaccessor)` for writing a number value and listening to number input changes. The value accessor is used by the `[FormControlDirective](formcontroldirective)`, `[FormControlName](formcontrolname)`, and `[NgModel](ngmodel)` directives. | | [``` PatternValidator ```](patternvalidator) | A directive that adds regex pattern validation to controls marked with the `[pattern](patternvalidator)` attribute. The regex must match the entire control value. The directive is provided with the `[NG\_VALIDATORS](ng_validators)` multi-provider list. | | [``` RadioControlValueAccessor ```](radiocontrolvalueaccessor) | The `[ControlValueAccessor](controlvalueaccessor)` for writing radio control values and listening to radio control changes. The value accessor is used by the `[FormControlDirective](formcontroldirective)`, `[FormControlName](formcontrolname)`, and `[NgModel](ngmodel)` directives. | | [``` RangeValueAccessor ```](rangevalueaccessor) | The `[ControlValueAccessor](controlvalueaccessor)` for writing a range value and listening to range input changes. The value accessor is used by the `[FormControlDirective](formcontroldirective)`, `[FormControlName](formcontrolname)`, and `[NgModel](ngmodel)` directives. | | [``` RequiredValidator ```](requiredvalidator) | A directive that adds the `required` validator to any controls marked with the `required` attribute. The directive is provided with the `[NG\_VALIDATORS](ng_validators)` multi-provider list. | | [``` SelectControlValueAccessor ```](selectcontrolvalueaccessor) | The `[ControlValueAccessor](controlvalueaccessor)` for writing select control values and listening to select control changes. The value accessor is used by the `[FormControlDirective](formcontroldirective)`, `[FormControlName](formcontrolname)`, and `[NgModel](ngmodel)` directives. | | [``` SelectMultipleControlValueAccessor ```](selectmultiplecontrolvalueaccessor) | The `[ControlValueAccessor](controlvalueaccessor)` for writing multi-select control values and listening to multi-select control changes. The value accessor is used by the `[FormControlDirective](formcontroldirective)`, `[FormControlName](formcontrolname)`, and `[NgModel](ngmodel)` directives. | angular FormArray FormArray ========= `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Tracks the value and validity state of an array of `[FormControl](formcontrol)`, `[FormGroup](formgroup)` or `[FormArray](formarray)` instances. [See more...](formarray#description) ``` class FormArray<TControl extends AbstractControl<any> = any> extends AbstractControl<ɵTypedOrUntyped<TControl, ɵFormArrayValue<TControl>, any>, ɵTypedOrUntyped<TControl, ɵFormArrayRawValue<TControl>, any>> { constructor(controls: TControl[], validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]) controls: ɵTypedOrUntyped<TControl, Array<TControl>, Array<AbstractControl<any>>> length: number at(index: number): ɵTypedOrUntyped<TControl, TControl, AbstractControl<any>> push(control: TControl, options: { emitEvent?: boolean; } = {}): void insert(index: number, control: TControl, options: { emitEvent?: boolean; } = {}): void removeAt(index: number, options: { emitEvent?: boolean; } = {}): void setControl(index: number, control: TControl, options: { emitEvent?: boolean; } = {}): void setValue(value: ɵIsAny<TControl, any[], ɵRawValue<TControl>[]>, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void patchValue(value: ɵIsAny<TControl, any[], ɵValue<TControl>[]>, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void reset(value: ɵIsAny<TControl, any, ɵIsAny<TControl, any[], ɵValue<TControl>[]>> = [], options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void getRawValue(): ɵFormArrayRawValue<TControl> clear(options: { emitEvent?: boolean; } = {}): void // inherited from forms/AbstractControl constructor(validators: ValidatorFn | ValidatorFn[], asyncValidators: AsyncValidatorFn | AsyncValidatorFn[]) value: TValue validator: ValidatorFn | null asyncValidator: AsyncValidatorFn | null parent: FormGroup | FormArray | null status: FormControlStatus valid: boolean invalid: boolean pending: boolean disabled: boolean enabled: boolean errors: ValidationErrors | null pristine: boolean dirty: boolean touched: boolean untouched: boolean valueChanges: Observable<TValue> statusChanges: Observable<FormControlStatus> updateOn: FormHooks root: AbstractControl setValidators(validators: ValidatorFn | ValidatorFn[]): void setAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void addValidators(validators: ValidatorFn | ValidatorFn[]): void addAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void removeValidators(validators: ValidatorFn | ValidatorFn[]): void removeAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void hasValidator(validator: ValidatorFn): boolean hasAsyncValidator(validator: AsyncValidatorFn): boolean clearValidators(): void clearAsyncValidators(): void markAsTouched(opts: { onlySelf?: boolean; } = {}): void markAllAsTouched(): void markAsUntouched(opts: { onlySelf?: boolean; } = {}): void markAsDirty(opts: { onlySelf?: boolean; } = {}): void markAsPristine(opts: { onlySelf?: boolean; } = {}): void markAsPending(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void disable(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void enable(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void setParent(parent: FormGroup<any> | FormArray<any>): void abstract setValue(value: TRawValue, options?: Object): void abstract patchValue(value: TValue, options?: Object): void abstract reset(value?: TValue, options?: Object): void getRawValue(): any updateValueAndValidity(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void setErrors(errors: ValidationErrors, opts: { emitEvent?: boolean; } = {}): void get<P extends string | ((string | number)[])>(path: P): AbstractControl<ɵGetProperty<TRawValue, P>> | null getError(errorCode: string, path?: string | (string | number)[]): any hasError(errorCode: string, path?: string | (string | number)[]): boolean } ``` Description ----------- A `[FormArray](formarray)` aggregates the values of each child `[FormControl](formcontrol)` into an array. It calculates its status by reducing the status values of its children. For example, if one of the controls in a `[FormArray](formarray)` is invalid, the entire array becomes invalid. `[FormArray](formarray)` accepts one generic argument, which is the type of the controls inside. If you need a heterogenous array, use [`UntypedFormArray`](untypedformarray). `[FormArray](formarray)` is one of the four fundamental building blocks used to define forms in Angular, along with `[FormControl](formcontrol)`, `[FormGroup](formgroup)`, and `[FormRecord](formrecord)`. Further information is available in the [Usage Notes...](formarray#usage-notes) Constructor ----------- | | | --- | | Creates a new `[FormArray](formarray)` instance. This class is "final" and should not be extended. See the [public API notes](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes). | | `constructor(controls: TControl[], validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[])` Parameters | | | | | --- | --- | --- | | `controls` | `TControl[]` | An array of child controls. Each child control is given an index where it is registered. | | `validatorOrOpts` | `[ValidatorFn](validatorfn) | [AbstractControlOptions](abstractcontroloptions) | [ValidatorFn](validatorfn)[]` | A synchronous validator function, or an array of such functions, or an `[AbstractControlOptions](abstractcontroloptions)` object that contains validation functions and a validation trigger. Optional. Default is `undefined`. | | `asyncValidator` | `[AsyncValidatorFn](asyncvalidatorfn) | [AsyncValidatorFn](asyncvalidatorfn)[]` | A single async validator or array of async validator functions Optional. Default is `undefined`. | | Properties ---------- | Property | Description | | --- | --- | | `controls: ɵTypedOrUntyped<TControl, Array<TControl>, Array<[AbstractControl](abstractcontrol)<any>>>` | | | `length: number` | Read-Only Length of the control array. | Methods ------- | at() | | --- | | Get the `[AbstractControl](abstractcontrol)` at the given `index` in the array. | | `at(index: number): ɵTypedOrUntyped<TControl, TControl, AbstractControl<any>>` Parameters | | | | | --- | --- | --- | | `index` | `number` | Index in the array to retrieve the control. If `index` is negative, it will wrap around from the back, and if index is greatly negative (less than `-length`), the result is undefined. This behavior is the same as `Array.at(index)`. | Returns `ɵTypedOrUntyped<TControl, TControl, [AbstractControl](abstractcontrol)<any>>` | | push() | | --- | | Insert a new `[AbstractControl](abstractcontrol)` at the end of the array. | | `push(control: TControl, options: { emitEvent?: boolean; } = {}): void` Parameters | | | | | --- | --- | --- | | `control` | `TControl` | Form control to be inserted | | `options` | `object` | Specifies whether this FormArray instance should emit events after a new control is added.* `emitEvent`: When true or not supplied (the default), both the `statusChanges` and `valueChanges` observables emit events with the latest status and value when the control is inserted. When false, no events are emitted. Optional. Default is `{}`. | Returns `void` | | insert() | | --- | | Insert a new `[AbstractControl](abstractcontrol)` at the given `index` in the array. | | `insert(index: number, control: TControl, options: { emitEvent?: boolean; } = {}): void` Parameters | | | | | --- | --- | --- | | `index` | `number` | Index in the array to insert the control. If `index` is negative, wraps around from the back. If `index` is greatly negative (less than `-length`), prepends to the array. This behavior is the same as `Array.splice(index, 0, control)`. | | `control` | `TControl` | Form control to be inserted | | `options` | `object` | Specifies whether this FormArray instance should emit events after a new control is inserted.* `emitEvent`: When true or not supplied (the default), both the `statusChanges` and `valueChanges` observables emit events with the latest status and value when the control is inserted. When false, no events are emitted. Optional. Default is `{}`. | Returns `void` | | removeAt() | | --- | | Remove the control at the given `index` in the array. | | `removeAt(index: number, options: { emitEvent?: boolean; } = {}): void` Parameters | | | | | --- | --- | --- | | `index` | `number` | Index in the array to remove the control. If `index` is negative, wraps around from the back. If `index` is greatly negative (less than `-length`), removes the first element. This behavior is the same as `Array.splice(index, 1)`. | | `options` | `object` | Specifies whether this FormArray instance should emit events after a control is removed.* `emitEvent`: When true or not supplied (the default), both the `statusChanges` and `valueChanges` observables emit events with the latest status and value when the control is removed. When false, no events are emitted. Optional. Default is `{}`. | Returns `void` | | setControl() | | --- | | Replace an existing control. | | `setControl(index: number, control: TControl, options: { emitEvent?: boolean; } = {}): void` Parameters | | | | | --- | --- | --- | | `index` | `number` | Index in the array to replace the control. If `index` is negative, wraps around from the back. If `index` is greatly negative (less than `-length`), replaces the first element. This behavior is the same as `Array.splice(index, 1, control)`. | | `control` | `TControl` | The `[AbstractControl](abstractcontrol)` control to replace the existing control | | `options` | `object` | Specifies whether this FormArray instance should emit events after an existing control is replaced with a new one.* `emitEvent`: When true or not supplied (the default), both the `statusChanges` and `valueChanges` observables emit events with the latest status and value when the control is replaced with a new one. When false, no events are emitted. Optional. Default is `{}`. | Returns `void` | | setValue() | | --- | | Sets the value of the `[FormArray](formarray)`. It accepts an array that matches the structure of the control. | | `setValue(value: ɵIsAny<TControl, any[], ɵRawValue<TControl>[]>, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void` Parameters | | | | | --- | --- | --- | | `value` | `ɵIsAny<TControl, any[], ɵRawValue<TControl>[]>` | Array of values for the controls | | `options` | `object` | Configure options that determine how the control propagates changes and emits events after the value changes* `onlySelf`: When true, each change only affects this control, and not its parent. Default is false. * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and `valueChanges` observables emit events with the latest status and value when the control value is updated. When false, no events are emitted. The configuration options are passed to the [updateValueAndValidity](abstractcontrol#updateValueAndValidity) method. Optional. Default is `{}`. | Returns `void` | | This method performs strict checks, and throws an error if you try to set the value of a control that doesn't exist or if you exclude the value of a control. | | Usage Notes Set the values for the controls in the form array ``` const arr = new FormArray([ new FormControl(), new FormControl() ]); console.log(arr.value); // [null, null] arr.setValue(['Nancy', 'Drew']); console.log(arr.value); // ['Nancy', 'Drew'] ``` | | patchValue() | | --- | | Patches the value of the `[FormArray](formarray)`. It accepts an array that matches the structure of the control, and does its best to match the values to the correct controls in the group. | | `patchValue(value: ɵIsAny<TControl, any[], ɵValue<TControl>[]>, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void` Parameters | | | | | --- | --- | --- | | `value` | `ɵIsAny<TControl, any[], ɵValue<TControl>[]>` | Array of latest values for the controls | | `options` | `object` | Configure options that determine how the control propagates changes and emits events after the value changes* `onlySelf`: When true, each change only affects this control, and not its parent. Default is false. * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and `valueChanges` observables emit events with the latest status and value when the control value is updated. When false, no events are emitted. The configuration options are passed to the [updateValueAndValidity](abstractcontrol#updateValueAndValidity) method. Optional. Default is `{}`. | Returns `void` | | It accepts both super-sets and sub-sets of the array without throwing an error. | | Usage Notes Patch the values for controls in a form array ``` const arr = new FormArray([ new FormControl(), new FormControl() ]); console.log(arr.value); // [null, null] arr.patchValue(['Nancy']); console.log(arr.value); // ['Nancy', null] ``` | | reset() | | --- | | Resets the `[FormArray](formarray)` and all descendants are marked `pristine` and `untouched`, and the value of all descendants to null or null maps. | | `reset(value: ɵIsAny<TControl, any, ɵIsAny<TControl, any[], ɵValue<TControl>[]>> = [], options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void` Parameters | | | | | --- | --- | --- | | `value` | `ɵIsAny<TControl, any, ɵIsAny<TControl, any[], ɵValue<TControl>[]>>` | Array of values for the controls Optional. Default is `[]`. | | `options` | `object` | Configure options that determine how the control propagates changes and emits events after the value changes* `onlySelf`: When true, each change only affects this control, and not its parent. Default is false. * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and `valueChanges` observables emit events with the latest status and value when the control is reset. When false, no events are emitted. The configuration options are passed to the [updateValueAndValidity](abstractcontrol#updateValueAndValidity) method. Optional. Default is `{}`. | Returns `void` | | You reset to a specific form state by passing in an array of states that matches the structure of the control. The state is a standalone value or a form state object with both a value and a disabled status. | | Usage Notes Reset the values in a form array ``` const arr = new FormArray([ new FormControl(), new FormControl() ]); arr.reset(['name', 'last name']); console.log(arr.value); // ['name', 'last name'] ``` Reset the values in a form array and the disabled status for the first control ``` arr.reset([ {value: 'name', disabled: true}, 'last' ]); console.log(arr.value); // ['last'] console.log(arr.at(0).status); // 'DISABLED' ``` | | getRawValue() | | --- | | The aggregate value of the array, including any disabled controls. | | `getRawValue(): ɵFormArrayRawValue<TControl>` Parameters There are no parameters. Returns `ɵFormArrayRawValue<TControl>` | | Reports all values regardless of disabled status. | | clear() | | --- | | Remove all controls in the `[FormArray](formarray)`. | | `clear(options: { emitEvent?: boolean; } = {}): void` Parameters | | | | | --- | --- | --- | | `options` | `object` | Specifies whether this FormArray instance should emit events after all controls are removed.* `emitEvent`: When true or not supplied (the default), both the `statusChanges` and `valueChanges` observables emit events with the latest status and value when all controls in this FormArray instance are removed. When false, no events are emitted. Optional. Default is `{}`. | Returns `void` | | Usage Notes Remove all elements from a FormArray ``` const arr = new FormArray([ new FormControl(), new FormControl() ]); console.log(arr.length); // 2 arr.clear(); console.log(arr.length); // 0 ``` It's a simpler and more efficient alternative to removing all elements one by one: ``` const arr = new FormArray([ new FormControl(), new FormControl() ]); while (arr.length) { arr.removeAt(0); } ``` | Usage notes ----------- ### Create an array of form controls ``` const arr = new FormArray([ new FormControl('Nancy', Validators.minLength(2)), new FormControl('Drew'), ]); console.log(arr.value); // ['Nancy', 'Drew'] console.log(arr.status); // 'VALID' ``` ### Create a form array with array-level validators You include array-level validators and async validators. These come in handy when you want to perform validation that considers the value of more than one child control. The two types of validators are passed in separately as the second and third arg respectively, or together as part of an options object. ``` const arr = new FormArray([ new FormControl('Nancy'), new FormControl('Drew') ], {validators: myValidator, asyncValidators: myAsyncValidator}); ``` ### Set the updateOn property for all controls in a form array The options object is used to set a default value for each child control's `updateOn` property. If you set `updateOn` to `'blur'` at the array level, all child controls default to 'blur', unless the child has explicitly specified a different `updateOn` value. ``` const arr = new FormArray([ new FormControl() ], {updateOn: 'blur'}); ``` ### Adding or removing controls from a form array To change the controls in the array, use the `push`, `insert`, `removeAt` or `clear` methods in `[FormArray](formarray)` itself. These methods ensure the controls are properly tracked in the form's hierarchy. Do not modify the array of `[AbstractControl](abstractcontrol)`s used to instantiate the `[FormArray](formarray)` directly, as that result in strange and unexpected behavior such as broken change detection.
programming_docs
angular RadioControlValueAccessor RadioControlValueAccessor ========================= `directive` The `[ControlValueAccessor](controlvalueaccessor)` for writing radio control values and listening to radio control changes. The value accessor is used by the `[FormControlDirective](formcontroldirective)`, `[FormControlName](formcontrolname)`, and `[NgModel](ngmodel)` directives. Exported from ------------- * [``` ReactiveFormsModule ```](reactiveformsmodule) * [``` FormsModule ```](formsmodule) Selectors --------- * `input[type=radio][[formControlName](formcontrolname)]` * `input[type=radio][formControl]` * `input[type=radio][[ngModel](ngmodel)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)()name: string` | Tracks the name of the radio input element. | | `@[Input](../core/input)()[formControlName](formcontrolname): string` | Tracks the name of the `[FormControl](formcontrol)` bound to the directive. The name corresponds to a key in the parent `[FormGroup](formgroup)` or `[FormArray](formarray)`. | | `@[Input](../core/input)()value: any` | Tracks the value of the radio input element | Description ----------- ### Using radio buttons with reactive form directives The follow example shows how to use radio buttons in a reactive form. When using radio buttons in a reactive form, radio buttons in the same group should have the same `[formControlName](formcontrolname)`. Providing a `name` attribute is optional. ``` import {Component} from '@angular/core'; import {FormControl, FormGroup} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form [formGroup]="form"> <input type="radio" formControlName="food" value="beef" > Beef <input type="radio" formControlName="food" value="lamb"> Lamb <input type="radio" formControlName="food" value="fish"> Fish </form> <p>Form value: {{ form.value | json }}</p> <!-- {food: 'lamb' } --> `, }) export class ReactiveRadioButtonComp { form = new FormGroup({ food: new FormControl('lamb'), }); } ``` Methods ------- | fireUncheck() | | --- | | Sets the "value" on the radio input element and unchecks it. | | `fireUncheck(value: any): void` Parameters | | | | | --- | --- | --- | | `value` | `any` | | Returns `void` | angular SelectControlValueAccessor SelectControlValueAccessor ========================== `directive` The `[ControlValueAccessor](controlvalueaccessor)` for writing select control values and listening to select control changes. The value accessor is used by the `[FormControlDirective](formcontroldirective)`, `[FormControlName](formcontrolname)`, and `[NgModel](ngmodel)` directives. Exported from ------------- * [``` ReactiveFormsModule ```](reactiveformsmodule) * [``` FormsModule ```](formsmodule) Selectors --------- * `select*:not([[multiple](selectmultiplecontrolvalueaccessor)])*[[formControlName](formcontrolname)]` * `select*:not([[multiple](selectmultiplecontrolvalueaccessor)])*[formControl]` * `select*:not([[multiple](selectmultiplecontrolvalueaccessor)])*[[ngModel](ngmodel)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)()compareWith: (o1: any, o2: any) => boolean` | Write-Only Tracks the option comparison algorithm for tracking identities when checking for changes. | Description ----------- ### Using select controls in a reactive form The following examples show how to use a select control in a reactive form. ``` import {Component} from '@angular/core'; import {FormControl, FormGroup} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form [formGroup]="form"> <select formControlName="state"> <option *ngFor="let state of states" [ngValue]="state"> {{ state.abbrev }} </option> </select> </form> <p>Form value: {{ form.value | json }}</p> <!-- {state: {name: 'New York', abbrev: 'NY'} } --> `, }) export class ReactiveSelectComp { states = [ {name: 'Arizona', abbrev: 'AZ'}, {name: 'California', abbrev: 'CA'}, {name: 'Colorado', abbrev: 'CO'}, {name: 'New York', abbrev: 'NY'}, {name: 'Pennsylvania', abbrev: 'PA'}, ]; form = new FormGroup({ state: new FormControl(this.states[3]), }); } ``` ### Using select controls in a template-driven form To use a select in a template-driven form, simply add an `[ngModel](ngmodel)` and a `name` attribute to the main `<select>` tag. ``` import {Component} from '@angular/core'; @Component({ selector: 'example-app', template: ` <form #f="ngForm"> <select name="state" ngModel> <option value="" disabled>Choose a state</option> <option *ngFor="let state of states" [ngValue]="state"> {{ state.abbrev }} </option> </select> </form> <p>Form value: {{ f.value | json }}</p> <!-- example value: {state: {name: 'New York', abbrev: 'NY'} } --> `, }) export class SelectControlComp { states = [ {name: 'Arizona', abbrev: 'AZ'}, {name: 'California', abbrev: 'CA'}, {name: 'Colorado', abbrev: 'CO'}, {name: 'New York', abbrev: 'NY'}, {name: 'Pennsylvania', abbrev: 'PA'}, ]; } ``` ### Customizing option selection Angular uses object identity to select option. It's possible for the identities of items to change while the data does not. This can happen, for example, if the items are produced from an RPC to the server, and that RPC is re-run. Even if the data hasn't changed, the second response will produce objects with different identities. To customize the default option comparison algorithm, `<select>` supports `compareWith` input. `compareWith` takes a **function** which has two arguments: `option1` and `option2`. If `compareWith` is given, Angular selects option by the return value of the function. ``` const selectedCountriesControl = new FormControl(); ``` ``` <select [compareWith]="compareFn" [formControl]="selectedCountriesControl"> <option *ngFor="let country of countries" [ngValue]="country"> {{country.name}} </option> </select> compareFn(c1: Country, c2: Country): boolean { return c1 && c2 ? c1.id === c2.id : c1 === c2; } ``` **Note:** We listen to the 'change' event because 'input' events aren't fired for selects in IE, see: <https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event#browser_compatibility> angular RequiredValidator RequiredValidator ================= `directive` A directive that adds the `required` validator to any controls marked with the `required` attribute. The directive is provided with the `[NG\_VALIDATORS](ng_validators)` multi-provider list. See also -------- * [Form Validation](../../guide/form-validation) Exported from ------------- * [``` FormsModule ```](formsmodule) * [``` ReactiveFormsModule ```](reactiveformsmodule) Selectors --------- * `*:not([type=checkbox])*[required][[formControlName](formcontrolname)]` * `*:not([type=checkbox])*[required][formControl]` * `*:not([type=checkbox])*[required][[ngModel](ngmodel)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)()required: boolean | string` | Tracks changes to the required attribute bound to this directive. | Description ----------- ### Adding a required validator using template-driven forms ``` <input name="fullName" ngModel required> ``` angular ValidationErrors ValidationErrors ================ `type-alias` Defines the map of errors returned from failed validation checks. ``` type ValidationErrors = { [key: string]: any; }; ``` angular FormControlDirective FormControlDirective ==================== `directive` Synchronizes a standalone `[FormControl](formcontrol)` instance to a form control element. [See more...](formcontroldirective#description) See also -------- * [Reactive Forms Guide](../../guide/reactive-forms) * `[FormControl](formcontrol)` * `[AbstractControl](abstractcontrol)` Exported from ------------- * [``` ReactiveFormsModule ```](reactiveformsmodule) Selectors --------- * `[formControl]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)('formControl')form: [FormControl](formcontrol)` | Tracks the `[FormControl](formcontrol)` instance bound to the directive. | | `@[Input](../core/input)('disabled')isDisabled: boolean` | Write-Only Triggers a warning in dev mode that this input should not be used with reactive forms. | | `@[Input](../core/input)('[ngModel](ngmodel)')model: any` | **Deprecated** as of v6 | | `@[Output](../core/output)('ngModelChange')update: [EventEmitter](../core/eventemitter)` | **Deprecated** as of v6 | | `path: string[]` | Read-Only Returns an array that represents the path from the top-level form to this control. Each index is the string name of the control on that level. | | `control: [FormControl](formcontrol)` | Read-Only The `[FormControl](formcontrol)` bound to this directive. | ### Inherited from `[NgControl](ngcontrol)` * `[name: string | number | null](ngcontrol#name)` * `[valueAccessor: ControlValueAccessor | null](ngcontrol#valueAccessor)` ### Inherited from `[AbstractControlDirective](abstractcontroldirective)` * `[abstract control: AbstractControl | null](abstractcontroldirective#control)` * `[value: any](abstractcontroldirective#value)` * `[valid: boolean | null](abstractcontroldirective#valid)` * `[invalid: boolean | null](abstractcontroldirective#invalid)` * `[pending: boolean | null](abstractcontroldirective#pending)` * `[disabled: boolean | null](abstractcontroldirective#disabled)` * `[enabled: boolean | null](abstractcontroldirective#enabled)` * `[errors: ValidationErrors | null](abstractcontroldirective#errors)` * `[pristine: boolean | null](abstractcontroldirective#pristine)` * `[dirty: boolean | null](abstractcontroldirective#dirty)` * `[touched: boolean | null](abstractcontroldirective#touched)` * `[status: string | null](abstractcontroldirective#status)` * `[untouched: boolean | null](abstractcontroldirective#untouched)` * `[statusChanges: Observable<any> | null](abstractcontroldirective#statusChanges)` * `[valueChanges: Observable<any> | null](abstractcontroldirective#valueChanges)` * `[path: string[] | null](abstractcontroldirective#path)` * `[validator: ValidatorFn | null](abstractcontroldirective#validator)` * `[asyncValidator: AsyncValidatorFn | null](abstractcontroldirective#asyncValidator)` Template variable references ---------------------------- | Identifier | Usage | | --- | --- | | `[ngForm](ngform)` | `#myTemplateVar="[ngForm](ngform)"` | Description ----------- Note that support for using the `[ngModel](ngmodel)` input property and `ngModelChange` event with reactive form directives was deprecated in Angular v6 and is scheduled for removal in a future version of Angular. For details, see [Deprecated features](../../guide/deprecations#ngmodel-with-reactive-forms). The following example shows how to register a standalone control and set its value. ``` import {Component} from '@angular/core'; import {FormControl, Validators} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <input [formControl]="control"> <p>Value: {{ control.value }}</p> <p>Validation status: {{ control.status }}</p> <button (click)="setValue()">Set value</button> `, }) export class SimpleFormControl { control: FormControl = new FormControl('value', Validators.minLength(2)); setValue() { this.control.setValue('new value'); } } ``` Methods ------- | viewToModelUpdate() | | --- | | Sets the new value for the view model and emits an `ngModelChange` event. | | `viewToModelUpdate(newValue: any): void` Parameters | | | | | --- | --- | --- | | `newValue` | `any` | The new value for the view model. | Returns `void` | ### Inherited from `[NgControl](ngcontrol)` * `[abstract viewToModelUpdate(newValue: any): void](ngcontrol#viewToModelUpdate)` ### Inherited from `[AbstractControlDirective](abstractcontroldirective)` * `[reset(value: any = undefined): void](abstractcontroldirective#reset)` * `[hasError(errorCode: string, path?: string | (string | number)[]): boolean](abstractcontroldirective#hasError)` * `[getError(errorCode: string, path?: string | (string | number)[]): any](abstractcontroldirective#getError)` angular NgControl NgControl ========= `class` A base class that all `[FormControl](formcontrol)`-based directives extend. It binds a `[FormControl](formcontrol)` object to a DOM element. ``` abstract class NgControl extends AbstractControlDirective { name: string | number | null valueAccessor: ControlValueAccessor | null abstract viewToModelUpdate(newValue: any): void // inherited from forms/AbstractControlDirective abstract control: AbstractControl | null value: any valid: boolean | null invalid: boolean | null pending: boolean | null disabled: boolean | null enabled: boolean | null errors: ValidationErrors | null pristine: boolean | null dirty: boolean | null touched: boolean | null status: string | null untouched: boolean | null statusChanges: Observable<any> | null valueChanges: Observable<any> | null path: string[] | null validator: ValidatorFn | null asyncValidator: AsyncValidatorFn | null reset(value: any = undefined): void hasError(errorCode: string, path?: string | (string | number)[]): boolean getError(errorCode: string, path?: string | (string | number)[]): any } ``` Subclasses ---------- * `[NgModel](ngmodel)` * `[FormControlDirective](formcontroldirective)` * `[FormControlName](formcontrolname)` Properties ---------- | Property | Description | | --- | --- | | `name: string | number | null` | The name for the control | | `valueAccessor: [ControlValueAccessor](controlvalueaccessor) | null` | The value accessor for the control | Methods ------- | viewToModelUpdate() | | --- | | The callback method to update the model from the view when requested | | `abstract viewToModelUpdate(newValue: any): void` Parameters | | | | | --- | --- | --- | | `newValue` | `any` | The new value for the view | Returns `void` | angular CheckboxControlValueAccessor CheckboxControlValueAccessor ============================ `directive` A `[ControlValueAccessor](controlvalueaccessor)` for writing a value and listening to changes on a checkbox input element. Exported from ------------- * [``` ReactiveFormsModule ```](reactiveformsmodule) * [``` FormsModule ```](formsmodule) Selectors --------- * `input[type=checkbox][[formControlName](formcontrolname)]` * `input[type=checkbox][formControl]` * `input[type=checkbox][[ngModel](ngmodel)]` Description ----------- ### Using a checkbox with a reactive form. The following example shows how to use a checkbox with a reactive form. ``` const rememberLoginControl = new FormControl(); ``` ``` <input type="checkbox" [formControl]="rememberLoginControl"> ``` angular DefaultValueAccessor DefaultValueAccessor ==================== `directive` The default `[ControlValueAccessor](controlvalueaccessor)` for writing a value and listening to changes on input elements. The accessor is used by the `[FormControlDirective](formcontroldirective)`, `[FormControlName](formcontrolname)`, and `[NgModel](ngmodel)` directives. [See more...](defaultvalueaccessor#description) Exported from ------------- * [``` ReactiveFormsModule ```](reactiveformsmodule) * [``` FormsModule ```](formsmodule) Selectors --------- * `input*:not([type=checkbox])*[[formControlName](formcontrolname)]` * `[textarea](defaultvalueaccessor)[[formControlName](formcontrolname)]` * `input*:not([type=checkbox])*[formControl]` * `[textarea](defaultvalueaccessor)[formControl]` * `input*:not([type=checkbox])*[[ngModel](ngmodel)]` * `[textarea](defaultvalueaccessor)[[ngModel](ngmodel)]` * `[[ngDefaultControl](defaultvalueaccessor)]` Description ----------- ### Using the default value accessor The following example shows how to use an input element that activates the default value accessor (in this case, a text field). ``` const firstNameControl = new FormControl(); ``` ``` <input type="text" [formControl]="firstNameControl"> ``` This value accessor is used by default for `<input type="text">` and `<[textarea](defaultvalueaccessor)>` elements, but you could also use it for custom components that have similar behavior and do not require special processing. In order to attach the default value accessor to a custom element, add the `[ngDefaultControl](defaultvalueaccessor)` attribute as shown below. ``` <custom-input-component ngDefaultControl [(ngModel)]="value"></custom-input-component> ``` angular ReactiveFormsModule ReactiveFormsModule =================== `ngmodule` Exports the required infrastructure and directives for reactive forms, making them available for import by NgModules that import this module. [See more...](reactiveformsmodule#description) ``` class ReactiveFormsModule { static withConfig(opts: { warnOnNgModelWithFormControl?: "always" | "never" | "once"; callSetDisabledState?: SetDisabledStateOption; }): ModuleWithProviders<ReactiveFormsModule> } ``` See also -------- * [Forms Overview](../../guide/forms-overview) * [Reactive Forms Guide](../../guide/reactive-forms) Description ----------- Providers associated with this module: * `[FormBuilder](formbuilder)` * `RadioControlRegistry` Static methods -------------- | withConfig() | | --- | | Provides options for configuring the reactive forms module. | | `static withConfig(opts: { warnOnNgModelWithFormControl?: "always" | "never" | "once"; callSetDisabledState?: SetDisabledStateOption; }): ModuleWithProviders<ReactiveFormsModule>` Parameters | | | | | --- | --- | --- | | `opts` | `object` | An object of configuration options* `warnOnNgModelWithFormControl` Configures when to emit a warning when an `[ngModel](ngmodel)` binding is used with reactive form directives. * `callSetDisabledState` Configures whether to `always` call `setDisabledState`, which is more correct, or to only call it `whenDisabled`, which is the legacy behavior. | Returns `[ModuleWithProviders](../core/modulewithproviders)<[ReactiveFormsModule](reactiveformsmodule)>` | Directives ---------- | Name | Description | | --- | --- | | [``` CheckboxControlValueAccessor ```](checkboxcontrolvalueaccessor) | A `[ControlValueAccessor](controlvalueaccessor)` for writing a value and listening to changes on a checkbox input element. | | [``` CheckboxRequiredValidator ```](checkboxrequiredvalidator) | A Directive that adds the `required` validator to checkbox controls marked with the `required` attribute. The directive is provided with the `[NG\_VALIDATORS](ng_validators)` multi-provider list. | | [``` DefaultValueAccessor ```](defaultvalueaccessor) | The default `[ControlValueAccessor](controlvalueaccessor)` for writing a value and listening to changes on input elements. The accessor is used by the `[FormControlDirective](formcontroldirective)`, `[FormControlName](formcontrolname)`, and `[NgModel](ngmodel)` directives. | | [``` EmailValidator ```](emailvalidator) | A directive that adds the `[email](emailvalidator)` validator to controls marked with the `[email](emailvalidator)` attribute. The directive is provided with the `[NG\_VALIDATORS](ng_validators)` multi-provider list. | | [``` FormArrayName ```](formarrayname) | Syncs a nested `[FormArray](formarray)` to a DOM element. | | [``` FormControlDirective ```](formcontroldirective) | Synchronizes a standalone `[FormControl](formcontrol)` instance to a form control element. | | [``` FormControlName ```](formcontrolname) | Syncs a `[FormControl](formcontrol)` in an existing `[FormGroup](formgroup)` to a form control element by name. | | [``` FormGroupDirective ```](formgroupdirective) | Binds an existing `[FormGroup](formgroup)` or `[FormRecord](formrecord)` to a DOM element. | | [``` FormGroupName ```](formgroupname) | Syncs a nested `[FormGroup](formgroup)` or `[FormRecord](formrecord)` to a DOM element. | | [``` MaxLengthValidator ```](maxlengthvalidator) | A directive that adds max length validation to controls marked with the `[maxlength](maxlengthvalidator)` attribute. The directive is provided with the `[NG\_VALIDATORS](ng_validators)` multi-provider list. | | [``` MaxValidator ```](maxvalidator) | A directive which installs the [`MaxValidator`](maxvalidator) for any `[formControlName](formcontrolname)`, `formControl`, or control with `[ngModel](ngmodel)` that also has a `[max](maxvalidator)` attribute. | | [``` MinLengthValidator ```](minlengthvalidator) | A directive that adds minimum length validation to controls marked with the `[minlength](minlengthvalidator)` attribute. The directive is provided with the `[NG\_VALIDATORS](ng_validators)` multi-provider list. | | [``` MinValidator ```](minvalidator) | A directive which installs the [`MinValidator`](minvalidator) for any `[formControlName](formcontrolname)`, `formControl`, or control with `[ngModel](ngmodel)` that also has a `[min](minvalidator)` attribute. | | [``` NgControlStatus ```](ngcontrolstatus) | Directive automatically applied to Angular form controls that sets CSS classes based on control status. | | [``` NgControlStatusGroup ```](ngcontrolstatusgroup) | Directive automatically applied to Angular form groups that sets CSS classes based on control status (valid/invalid/dirty/etc). On groups, this includes the additional class ng-submitted. | | [``` NgSelectOption ```](ngselectoption) | Marks `<option>` as dynamic, so Angular can be notified when options change. | | [``` NumberValueAccessor ```](numbervalueaccessor) | The `[ControlValueAccessor](controlvalueaccessor)` for writing a number value and listening to number input changes. The value accessor is used by the `[FormControlDirective](formcontroldirective)`, `[FormControlName](formcontrolname)`, and `[NgModel](ngmodel)` directives. | | [``` PatternValidator ```](patternvalidator) | A directive that adds regex pattern validation to controls marked with the `[pattern](patternvalidator)` attribute. The regex must match the entire control value. The directive is provided with the `[NG\_VALIDATORS](ng_validators)` multi-provider list. | | [``` RadioControlValueAccessor ```](radiocontrolvalueaccessor) | The `[ControlValueAccessor](controlvalueaccessor)` for writing radio control values and listening to radio control changes. The value accessor is used by the `[FormControlDirective](formcontroldirective)`, `[FormControlName](formcontrolname)`, and `[NgModel](ngmodel)` directives. | | [``` RangeValueAccessor ```](rangevalueaccessor) | The `[ControlValueAccessor](controlvalueaccessor)` for writing a range value and listening to range input changes. The value accessor is used by the `[FormControlDirective](formcontroldirective)`, `[FormControlName](formcontrolname)`, and `[NgModel](ngmodel)` directives. | | [``` RequiredValidator ```](requiredvalidator) | A directive that adds the `required` validator to any controls marked with the `required` attribute. The directive is provided with the `[NG\_VALIDATORS](ng_validators)` multi-provider list. | | [``` SelectControlValueAccessor ```](selectcontrolvalueaccessor) | The `[ControlValueAccessor](controlvalueaccessor)` for writing select control values and listening to select control changes. The value accessor is used by the `[FormControlDirective](formcontroldirective)`, `[FormControlName](formcontrolname)`, and `[NgModel](ngmodel)` directives. | | [``` SelectMultipleControlValueAccessor ```](selectmultiplecontrolvalueaccessor) | The `[ControlValueAccessor](controlvalueaccessor)` for writing multi-select control values and listening to multi-select control changes. The value accessor is used by the `[FormControlDirective](formcontroldirective)`, `[FormControlName](formcontrolname)`, and `[NgModel](ngmodel)` directives. |
programming_docs
angular MaxValidator MaxValidator ============ `directive` A directive which installs the [`MaxValidator`](maxvalidator) for any `[formControlName](formcontrolname)`, `formControl`, or control with `[ngModel](ngmodel)` that also has a `[max](maxvalidator)` attribute. See also -------- * [Form Validation](../../guide/form-validation) Exported from ------------- * [``` ReactiveFormsModule ```](reactiveformsmodule) * [``` FormsModule ```](formsmodule) Selectors --------- * `input[type=number][[max](maxvalidator)][[formControlName](formcontrolname)]` * `input[type=number][[max](maxvalidator)][formControl]` * `input[type=number][[max](maxvalidator)][[ngModel](ngmodel)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)()[max](maxvalidator): string | number | null` | Tracks changes to the max bound to this directive. | Description ----------- ### Adding a max validator The following example shows how to add a max validator to an input attached to an ngModel binding. ``` <input type="number" ngModel max="4"> ``` angular Validator Validator ========= `interface` An interface implemented by classes that perform synchronous validation. ``` interface Validator { validate(control: AbstractControl<any, any>): ValidationErrors | null registerOnValidatorChange(fn: () => void)?: void } ``` Child interfaces ---------------- * `[AsyncValidator](asyncvalidator)` Methods ------- | validate() | | --- | | Method that performs synchronous validation against the provided control. | | `validate(control: AbstractControl<any, any>): ValidationErrors | null` Parameters | | | | | --- | --- | --- | | `control` | `[AbstractControl](abstractcontrol)<any, any>` | The control to validate against. | Returns `[ValidationErrors](validationerrors) | null`: A map of validation errors if validation fails, otherwise null. | | registerOnValidatorChange() | | --- | | Registers a callback function to call when the validator inputs change. | | `registerOnValidatorChange(fn: () => void)?: void` Parameters | | | | | --- | --- | --- | | `fn` | `() => void` | The callback function | Returns `void` | Usage notes ----------- ### Provide a custom validator The following example implements the `[Validator](validator)` interface to create a validator directive with a custom error key. ``` @Directive({ selector: '[customValidator]', providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}] }) class CustomValidatorDirective implements Validator { validate(control: AbstractControl): ValidationErrors|null { return {'custom': true}; } } ``` angular ValidatorFn ValidatorFn =========== `interface` A function that receives a control and synchronously returns a map of validation errors if present, otherwise null. ``` interface ValidatorFn { (control: AbstractControl<any, any>): ValidationErrors | null } ``` Methods ------- | *call signature* | | --- | | `(control: AbstractControl<any, any>): ValidationErrors | null` Parameters | | | | | --- | --- | --- | | `control` | `[AbstractControl](abstractcontrol)<any, any>` | | Returns `[ValidationErrors](validationerrors) | null` | angular AbstractFormGroupDirective AbstractFormGroupDirective ========================== `directive` A base class for code shared between the `[NgModelGroup](ngmodelgroup)` and `[FormGroupName](formgroupname)` directives. Properties ---------- | Property | Description | | --- | --- | | `control: [FormGroup](formgroup)` | Read-Only The `[FormGroup](formgroup)` bound to this directive. | | `path: string[]` | Read-Only The path to this group from the top-level directive. | | `formDirective: [Form](form) | null` | Read-Only The top-level directive for this group if present, otherwise null. | ### Inherited from `[ControlContainer](controlcontainer)` * `[name: string | number | null](controlcontainer#name)` * `[formDirective: Form | null](controlcontainer#formDirective)` * `[path: string[] | null](controlcontainer#path)` ### Inherited from `[AbstractControlDirective](abstractcontroldirective)` * `[abstract control: AbstractControl | null](abstractcontroldirective#control)` * `[value: any](abstractcontroldirective#value)` * `[valid: boolean | null](abstractcontroldirective#valid)` * `[invalid: boolean | null](abstractcontroldirective#invalid)` * `[pending: boolean | null](abstractcontroldirective#pending)` * `[disabled: boolean | null](abstractcontroldirective#disabled)` * `[enabled: boolean | null](abstractcontroldirective#enabled)` * `[errors: ValidationErrors | null](abstractcontroldirective#errors)` * `[pristine: boolean | null](abstractcontroldirective#pristine)` * `[dirty: boolean | null](abstractcontroldirective#dirty)` * `[touched: boolean | null](abstractcontroldirective#touched)` * `[status: string | null](abstractcontroldirective#status)` * `[untouched: boolean | null](abstractcontroldirective#untouched)` * `[statusChanges: Observable<any> | null](abstractcontroldirective#statusChanges)` * `[valueChanges: Observable<any> | null](abstractcontroldirective#valueChanges)` * `[path: string[] | null](abstractcontroldirective#path)` * `[validator: ValidatorFn | null](abstractcontroldirective#validator)` * `[asyncValidator: AsyncValidatorFn | null](abstractcontroldirective#asyncValidator)` ### Inherited from `[AbstractControlDirective](abstractcontroldirective)` * `[reset(value: any = undefined): void](abstractcontroldirective#reset)` * `[hasError(errorCode: string, path?: string | (string | number)[]): boolean](abstractcontroldirective#hasError)` * `[getError(errorCode: string, path?: string | (string | number)[]): any](abstractcontroldirective#getError)` angular AsyncValidatorFn AsyncValidatorFn ================ `interface` A function that receives a control and returns a Promise or observable that emits validation errors if present, otherwise null. ``` interface AsyncValidatorFn { (control: AbstractControl<any, any>): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> } ``` Methods ------- | *call signature* | | --- | | `(control: AbstractControl<any, any>): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>` Parameters | | | | | --- | --- | --- | | `control` | `[AbstractControl](abstractcontrol)<any, any>` | | Returns `Promise<[ValidationErrors](validationerrors) | null> | Observable<[ValidationErrors](validationerrors) | null>` | angular UntypedFormArray UntypedFormArray ================ `type-alias` UntypedFormArray is a non-strongly-typed version of @see FormArray, which permits heterogenous controls. ``` type UntypedFormArray = FormArray<any>; ``` angular NonNullableFormBuilder NonNullableFormBuilder ====================== `class` `[NonNullableFormBuilder](nonnullableformbuilder)` is similar to [`FormBuilder`](formbuilder), but automatically constructed [`FormControl`](formcontrol) elements have `{nonNullable: true}` and are non-nullable. ``` abstract class NonNullableFormBuilder { abstract group<T extends {}>(controls: T, options?: AbstractControlOptions): FormGroup<{...} abstract record<T>(controls: { [key: string]: T; }, options?: AbstractControlOptions): FormRecord<ɵElement<T, never>> abstract array<T>(controls: T[], validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]): FormArray<ɵElement<T, never>> abstract control<T>(formState: T | FormControlState<T>, validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]): FormControl<T> } ``` Provided in ----------- * ``` 'root' ``` Methods ------- | group() | | --- | | Similar to `[FormBuilder](formbuilder)#group`, except any implicitly constructed `[FormControl](formcontrol)` will be non-nullable (i.e. it will have `nonNullable` set to true). Note that already-constructed controls will not be altered. | | `abstract group<T extends {}>(controls: T, options?: AbstractControlOptions): FormGroup<{ [K in keyof T]: ɵElement<T[K], never>; }>` Parameters | | | | | --- | --- | --- | | `controls` | `T` | | | `options` | `[AbstractControlOptions](abstractcontroloptions)` | Optional. Default is `undefined`. | Returns `[FormGroup](formgroup)<{ [K in keyof T]: ɵElement<T[K], never>; }>` | | record() | | --- | | Similar to `[FormBuilder](formbuilder)#record`, except any implicitly constructed `[FormControl](formcontrol)` will be non-nullable (i.e. it will have `nonNullable` set to true). Note that already-constructed controls will not be altered. | | `abstract record<T>(controls: { [key: string]: T; }, options?: AbstractControlOptions): FormRecord<ɵElement<T, never>>` Parameters | | | | | --- | --- | --- | | `controls` | `object` | | | `options` | `[AbstractControlOptions](abstractcontroloptions)` | Optional. Default is `undefined`. | Returns `[FormRecord](formrecord)<ɵElement<T, never>>` | | array() | | --- | | Similar to `[FormBuilder](formbuilder)#array`, except any implicitly constructed `[FormControl](formcontrol)` will be non-nullable (i.e. it will have `nonNullable` set to true). Note that already-constructed controls will not be altered. | | `abstract array<T>(controls: T[], validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]): FormArray<ɵElement<T, never>>` Parameters | | | | | --- | --- | --- | | `controls` | `T[]` | | | `validatorOrOpts` | `[ValidatorFn](validatorfn) | [AbstractControlOptions](abstractcontroloptions) | [ValidatorFn](validatorfn)[]` | Optional. Default is `undefined`. | | `asyncValidator` | `[AsyncValidatorFn](asyncvalidatorfn) | [AsyncValidatorFn](asyncvalidatorfn)[]` | Optional. Default is `undefined`. | Returns `[FormArray](formarray)<ɵElement<T, never>>` | | control() | | --- | | Similar to `[FormBuilder](formbuilder)#control`, except this overridden version of `control` forces `nonNullable` to be `true`, resulting in the control always being non-nullable. | | `abstract control<T>(formState: T | FormControlState<T>, validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]): FormControl<T>` Parameters | | | | | --- | --- | --- | | `formState` | `T | [FormControlState](formcontrolstate)<T>` | | | `validatorOrOpts` | `[ValidatorFn](validatorfn) | [AbstractControlOptions](abstractcontroloptions) | [ValidatorFn](validatorfn)[]` | Optional. Default is `undefined`. | | `asyncValidator` | `[AsyncValidatorFn](asyncvalidatorfn) | [AsyncValidatorFn](asyncvalidatorfn)[]` | Optional. Default is `undefined`. | Returns `[FormControl](formcontrol)<T>` | angular MinValidator MinValidator ============ `directive` A directive which installs the [`MinValidator`](minvalidator) for any `[formControlName](formcontrolname)`, `formControl`, or control with `[ngModel](ngmodel)` that also has a `[min](minvalidator)` attribute. See also -------- * [Form Validation](../../guide/form-validation) Exported from ------------- * [``` ReactiveFormsModule ```](reactiveformsmodule) * [``` FormsModule ```](formsmodule) Selectors --------- * `input[type=number][[min](minvalidator)][[formControlName](formcontrolname)]` * `input[type=number][[min](minvalidator)][formControl]` * `input[type=number][[min](minvalidator)][[ngModel](ngmodel)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)()[min](minvalidator): string | number | null` | Tracks changes to the min bound to this directive. | Description ----------- ### Adding a min validator The following example shows how to add a min validator to an input attached to an ngModel binding. ``` <input type="number" ngModel min="4"> ``` angular SelectMultipleControlValueAccessor SelectMultipleControlValueAccessor ================================== `directive` The `[ControlValueAccessor](controlvalueaccessor)` for writing multi-select control values and listening to multi-select control changes. The value accessor is used by the `[FormControlDirective](formcontroldirective)`, `[FormControlName](formcontrolname)`, and `[NgModel](ngmodel)` directives. See also -------- * `[SelectControlValueAccessor](selectcontrolvalueaccessor)` Exported from ------------- * [``` ReactiveFormsModule ```](reactiveformsmodule) * [``` FormsModule ```](formsmodule) Selectors --------- * `select[[multiple](selectmultiplecontrolvalueaccessor)][[formControlName](formcontrolname)]` * `select[[multiple](selectmultiplecontrolvalueaccessor)][formControl]` * `select[[multiple](selectmultiplecontrolvalueaccessor)][[ngModel](ngmodel)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)()compareWith: (o1: any, o2: any) => boolean` | Write-Only Tracks the option comparison algorithm for tracking identities when checking for changes. | Description ----------- ### Using a multi-select control The follow example shows you how to use a multi-select control with a reactive form. ``` const countryControl = new FormControl(); ``` ``` <select multiple name="countries" [formControl]="countryControl"> <option *ngFor="let country of countries" [ngValue]="country"> {{ country.name }} </option> </select> ``` ### Customizing option selection To customize the default option comparison algorithm, `<select>` supports `compareWith` input. See the `[SelectControlValueAccessor](selectcontrolvalueaccessor)` for usage. angular FormRecord FormRecord ========== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Tracks the value and validity state of a collection of `[FormControl](formcontrol)` instances, each of which has the same value type. [See more...](formrecord#description) ``` class FormRecord<TControl extends AbstractControl = AbstractControl, TControl> extends FormGroup<{ [key: string]: TControl; }> { registerControl(name: string, control: TControl): TControl addControl(name: string, control: TControl, options?: { emitEvent?: boolean; }): void removeControl(name: string, options?: { emitEvent?: boolean; }): void setControl(name: string, control: TControl, options?: { emitEvent?: boolean; }): void contains(controlName: string): boolean setValue(value: { [key: string]: ɵValue<TControl>; }, options?: { onlySelf?: boolean; emitEvent?: boolean; }): void patchValue(value: { [key: string]: ɵValue<TControl>; }, options?: { onlySelf?: boolean; emitEvent?: boolean; }): void reset(value?: { [key: string]: ɵValue<TControl>; }, options?: { onlySelf?: boolean; emitEvent?: boolean; }): void getRawValue(): {...} // inherited from forms/FormGroup constructor(controls: TControl, validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]) controls: ɵTypedOrUntyped<TControl, TControl, {...} registerControl<K extends string & keyof TControl>(name: K, control: TControl[K]): TControl[K] addControl<K extends string & keyof TControl>(name: K, control: Required<TControl>[K], options: { emitEvent?: boolean; } = {}): void removeControl(name: string, options: { emitEvent?: boolean; } = {}): void setControl<K extends string & keyof TControl>(name: K, control: TControl[K], options: { emitEvent?: boolean; } = {}): void contains<K extends string & keyof TControl>(controlName: K): boolean setValue(value: ɵIsAny<TControl, { [key: string]: any; }, { [K in keyof TControl]: ɵRawValue<TControl[K]>; }>, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void patchValue(value: ɵIsAny<TControl, { [key: string]: any; }, Partial<{ [K in keyof TControl]: ɵValue<TControl[K]>; }>>, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void reset(value: ɵIsAny<TControl, any, ɵIsAny<TControl, { [key: string]: any; }, Partial<{ [K in keyof TControl]: ɵValue<TControl[K]>; }>>> = {} as unknown as ɵFormGroupValue<TControl>, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void getRawValue(): ɵTypedOrUntyped<TControl, ɵFormGroupRawValue<TControl>, any> // inherited from forms/AbstractControl constructor(validators: ValidatorFn | ValidatorFn[], asyncValidators: AsyncValidatorFn | AsyncValidatorFn[]) value: TValue validator: ValidatorFn | null asyncValidator: AsyncValidatorFn | null parent: FormGroup | FormArray | null status: FormControlStatus valid: boolean invalid: boolean pending: boolean disabled: boolean enabled: boolean errors: ValidationErrors | null pristine: boolean dirty: boolean touched: boolean untouched: boolean valueChanges: Observable<TValue> statusChanges: Observable<FormControlStatus> updateOn: FormHooks root: AbstractControl setValidators(validators: ValidatorFn | ValidatorFn[]): void setAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void addValidators(validators: ValidatorFn | ValidatorFn[]): void addAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void removeValidators(validators: ValidatorFn | ValidatorFn[]): void removeAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void hasValidator(validator: ValidatorFn): boolean hasAsyncValidator(validator: AsyncValidatorFn): boolean clearValidators(): void clearAsyncValidators(): void markAsTouched(opts: { onlySelf?: boolean; } = {}): void markAllAsTouched(): void markAsUntouched(opts: { onlySelf?: boolean; } = {}): void markAsDirty(opts: { onlySelf?: boolean; } = {}): void markAsPristine(opts: { onlySelf?: boolean; } = {}): void markAsPending(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void disable(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void enable(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void setParent(parent: FormGroup<any> | FormArray<any>): void abstract setValue(value: TRawValue, options?: Object): void abstract patchValue(value: TValue, options?: Object): void abstract reset(value?: TValue, options?: Object): void getRawValue(): any updateValueAndValidity(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void setErrors(errors: ValidationErrors, opts: { emitEvent?: boolean; } = {}): void get<P extends string | ((string | number)[])>(path: P): AbstractControl<ɵGetProperty<TRawValue, P>> | null getError(errorCode: string, path?: string | (string | number)[]): any hasError(errorCode: string, path?: string | (string | number)[]): boolean } ``` Description ----------- `[FormRecord](formrecord)` is very similar to [`FormGroup`](formgroup), except it can be used with a dynamic keys, with controls added and removed as needed. `[FormRecord](formrecord)` accepts one generic argument, which describes the type of the controls it contains. Further information is available in the [Usage Notes...](formrecord#usage-notes) Methods ------- | registerControl() | | --- | | Registers a control with the records's list of controls. | | `registerControl(name: string, control: TControl): TControl` Parameters | | | | | --- | --- | --- | | `name` | `string` | | | `control` | `TControl` | | Returns `TControl` | | See `[FormGroup](formgroup)#registerControl` for additional information. | | addControl() | | --- | | Add a control to this group. | | `addControl(name: string, control: TControl, options?: { emitEvent?: boolean; }): void` Parameters | | | | | --- | --- | --- | | `name` | `string` | | | `control` | `TControl` | | | `options` | `object` | Optional. Default is `undefined`. | Returns `void` | | See `[FormGroup](formgroup)#addControl` for additional information. | | removeControl() | | --- | | Remove a control from this group. | | `removeControl(name: string, options?: { emitEvent?: boolean; }): void` Parameters | | | | | --- | --- | --- | | `name` | `string` | | | `options` | `object` | Optional. Default is `undefined`. | Returns `void` | | See `[FormGroup](formgroup)#removeControl` for additional information. | | setControl() | | --- | | Replace an existing control. | | `setControl(name: string, control: TControl, options?: { emitEvent?: boolean; }): void` Parameters | | | | | --- | --- | --- | | `name` | `string` | | | `control` | `TControl` | | | `options` | `object` | Optional. Default is `undefined`. | Returns `void` | | See `[FormGroup](formgroup)#setControl` for additional information. | | contains() | | --- | | Check whether there is an enabled control with the given name in the group. | | `contains(controlName: string): boolean` Parameters | | | | | --- | --- | --- | | `controlName` | `string` | | Returns `boolean` | | See `[FormGroup](formgroup)#contains` for additional information. | | setValue() | | --- | | Sets the value of the `[FormRecord](formrecord)`. It accepts an object that matches the structure of the group, with control names as keys. | | `setValue(value: { [key: string]: ɵValue<TControl>; }, options?: { onlySelf?: boolean; emitEvent?: boolean; }): void` Parameters | | | | | --- | --- | --- | | `value` | `object` | | | `options` | `object` | Optional. Default is `undefined`. | Returns `void` | | See `[FormGroup](formgroup)#setValue` for additional information. | | patchValue() | | --- | | Patches the value of the `[FormRecord](formrecord)`. It accepts an object with control names as keys, and does its best to match the values to the correct controls in the group. | | `patchValue(value: { [key: string]: ɵValue<TControl>; }, options?: { onlySelf?: boolean; emitEvent?: boolean; }): void` Parameters | | | | | --- | --- | --- | | `value` | `object` | | | `options` | `object` | Optional. Default is `undefined`. | Returns `void` | | See `[FormGroup](formgroup)#patchValue` for additional information. | | reset() | | --- | | Resets the `[FormRecord](formrecord)`, marks all descendants `pristine` and `untouched` and sets the value of all descendants to null. | | `reset(value?: { [key: string]: ɵValue<TControl>; }, options?: { onlySelf?: boolean; emitEvent?: boolean; }): void` Parameters | | | | | --- | --- | --- | | `value` | `object` | Optional. Default is `undefined`. | | `options` | `object` | Optional. Default is `undefined`. | Returns `void` | | See `[FormGroup](formgroup)#reset` for additional information. | | getRawValue() | | --- | | The aggregate value of the `[FormRecord](formrecord)`, including any disabled controls. | | `getRawValue(): { [key: string]: ɵRawValue<TControl>; }` Parameters There are no parameters. Returns `{ }` | | See `[FormGroup](formgroup)#getRawValue` for additional information. | Usage notes ----------- ``` let numbers = new FormRecord({bill: new FormControl('415-123-456')}); numbers.addControl('bob', new FormControl('415-234-567')); numbers.removeControl('bill'); ```
programming_docs
angular ControlContainer ControlContainer ================ `class` A base class for directives that contain multiple registered instances of `[NgControl](ngcontrol)`. Only used by the forms module. ``` abstract class ControlContainer extends AbstractControlDirective { name: string | number | null formDirective: Form | null path: string[] | null // inherited from forms/AbstractControlDirective abstract control: AbstractControl | null value: any valid: boolean | null invalid: boolean | null pending: boolean | null disabled: boolean | null enabled: boolean | null errors: ValidationErrors | null pristine: boolean | null dirty: boolean | null touched: boolean | null status: string | null untouched: boolean | null statusChanges: Observable<any> | null valueChanges: Observable<any> | null path: string[] | null validator: ValidatorFn | null asyncValidator: AsyncValidatorFn | null reset(value: any = undefined): void hasError(errorCode: string, path?: string | (string | number)[]): boolean getError(errorCode: string, path?: string | (string | number)[]): any } ``` Subclasses ---------- * `[AbstractFormGroupDirective](abstractformgroupdirective)` + `[NgModelGroup](ngmodelgroup)` + `[FormGroupName](formgroupname)` * `[NgForm](ngform)` * `[FormGroupDirective](formgroupdirective)` * `[FormArrayName](formarrayname)` Properties ---------- | Property | Description | | --- | --- | | `name: string | number | null` | The name for the control | | `formDirective: [Form](form) | null` | Read-Only The top-level form directive for the control. | | `path: string[] | null` | Read-Only The path to this group. | angular NgModelGroup NgModelGroup ============ `directive` Creates and binds a `[FormGroup](formgroup)` instance to a DOM element. [See more...](ngmodelgroup#description) Exported from ------------- * [``` FormsModule ```](formsmodule) Selectors --------- * `[[ngModelGroup](ngmodelgroup)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)('[ngModelGroup](ngmodelgroup)')name: string` | Tracks the name of the `[NgModelGroup](ngmodelgroup)` bound to the directive. The name corresponds to a key in the parent `[NgForm](ngform)`. | ### Inherited from `[AbstractFormGroupDirective](abstractformgroupdirective)` * `[control: FormGroup](abstractformgroupdirective#control)` * `[path: string[]](abstractformgroupdirective#path)` * `[formDirective: Form | null](abstractformgroupdirective#formDirective)` ### Inherited from `[ControlContainer](controlcontainer)` * `[name: string | number | null](controlcontainer#name)` * `[formDirective: Form | null](controlcontainer#formDirective)` * `[path: string[] | null](controlcontainer#path)` ### Inherited from `[AbstractControlDirective](abstractcontroldirective)` * `[abstract control: AbstractControl | null](abstractcontroldirective#control)` * `[value: any](abstractcontroldirective#value)` * `[valid: boolean | null](abstractcontroldirective#valid)` * `[invalid: boolean | null](abstractcontroldirective#invalid)` * `[pending: boolean | null](abstractcontroldirective#pending)` * `[disabled: boolean | null](abstractcontroldirective#disabled)` * `[enabled: boolean | null](abstractcontroldirective#enabled)` * `[errors: ValidationErrors | null](abstractcontroldirective#errors)` * `[pristine: boolean | null](abstractcontroldirective#pristine)` * `[dirty: boolean | null](abstractcontroldirective#dirty)` * `[touched: boolean | null](abstractcontroldirective#touched)` * `[status: string | null](abstractcontroldirective#status)` * `[untouched: boolean | null](abstractcontroldirective#untouched)` * `[statusChanges: Observable<any> | null](abstractcontroldirective#statusChanges)` * `[valueChanges: Observable<any> | null](abstractcontroldirective#valueChanges)` * `[path: string[] | null](abstractcontroldirective#path)` * `[validator: ValidatorFn | null](abstractcontroldirective#validator)` * `[asyncValidator: AsyncValidatorFn | null](abstractcontroldirective#asyncValidator)` Template variable references ---------------------------- | Identifier | Usage | | --- | --- | | `[ngModelGroup](ngmodelgroup)` | `#myTemplateVar="[ngModelGroup](ngmodelgroup)"` | Description ----------- This directive can only be used as a child of `[NgForm](ngform)` (within `<form>` tags). Use this directive to validate a sub-group of your form separately from the rest of your form, or if some values in your domain model make more sense to consume together in a nested object. Provide a name for the sub-group and it will become the key for the sub-group in the form's full value. If you need direct access, export the directive into a local template variable using `[ngModelGroup](ngmodelgroup)` (ex: `#myGroup="[ngModelGroup](ngmodelgroup)"`). ### Consuming controls in a grouping The following example shows you how to combine controls together in a sub-group of the form. ``` import {Component} from '@angular/core'; import {NgForm} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form #f="ngForm" (ngSubmit)="onSubmit(f)"> <p *ngIf="nameCtrl.invalid">Name is invalid.</p> <div ngModelGroup="name" #nameCtrl="ngModelGroup"> <input name="first" [ngModel]="name.first" minlength="2"> <input name="middle" [ngModel]="name.middle" maxlength="2"> <input name="last" [ngModel]="name.last" required> </div> <input name="email" ngModel> <button>Submit</button> </form> <button (click)="setValue()">Set value</button> `, }) export class NgModelGroupComp { name = {first: 'Nancy', middle: 'J', last: 'Drew'}; onSubmit(f: NgForm) { console.log(f.value); // {name: {first: 'Nancy', middle: 'J', last: 'Drew'}, email: ''} console.log(f.valid); // true } setValue() { this.name = {first: 'Bess', middle: 'S', last: 'Marvin'}; } } ``` ### Inherited from `[AbstractControlDirective](abstractcontroldirective)` * `[reset(value: any = undefined): void](abstractcontroldirective#reset)` * `[hasError(errorCode: string, path?: string | (string | number)[]): boolean](abstractcontroldirective#hasError)` * `[getError(errorCode: string, path?: string | (string | number)[]): any](abstractcontroldirective#getError)` angular FormBuilder FormBuilder =========== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Creates an `[AbstractControl](abstractcontrol)` from a user-specified configuration. [See more...](formbuilder#description) ``` class FormBuilder { nonNullable: NonNullableFormBuilder group(controls: { [key: string]: any; }, options: AbstractControlOptions | { [key: string]: any; } = null): FormGroup record<T>(controls: { [key: string]: T; }, options: AbstractControlOptions = null): FormRecord<ɵElement<T, null>> control<T>(formState: T | FormControlState<T>, validatorOrOpts?: ValidatorFn | FormControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]): FormControl array<T>(controls: T[], validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]): FormArray<ɵElement<T, null>> } ``` Subclasses ---------- * `[UntypedFormBuilder](untypedformbuilder)` See also -------- * [Reactive Forms Guide](../../guide/reactive-forms) Provided in ----------- * ``` 'root' ``` Description ----------- The `[FormBuilder](formbuilder)` provides syntactic sugar that shortens creating instances of a `[FormControl](formcontrol)`, `[FormGroup](formgroup)`, or `[FormArray](formarray)`. It reduces the amount of boilerplate needed to build complex forms. Properties ---------- | Property | Description | | --- | --- | | `nonNullable: [NonNullableFormBuilder](nonnullableformbuilder)` | Read-Only Returns a FormBuilder in which automatically constructed @see FormControl} elements have `{nonNullable: true}` and are non-nullable. **Constructing non-nullable controls** When constructing a control, it will be non-nullable, and will reset to its initial value. ``` let nnfb = new FormBuilder().nonNullable; let name = nnfb.control('Alex'); // FormControl<string> name.reset(); console.log(name); // 'Alex' ``` **Constructing non-nullable groups or arrays** When constructing a group or array, all automatically created inner controls will be non-nullable, and will reset to their initial values. ``` let nnfb = new FormBuilder().nonNullable; let name = nnfb.group({who: 'Alex'}); // FormGroup<{who: FormControl<string>}> name.reset(); console.log(name); // {who: 'Alex'} ``` **Constructing *nullable* fields on groups or arrays** It is still possible to have a nullable field. In particular, any `[FormControl](formcontrol)` which is *already* constructed will not be altered. For example: ``` let nnfb = new FormBuilder().nonNullable; // FormGroup<{who: FormControl<string|null>}> let name = nnfb.group({who: new FormControl('Alex')}); name.reset(); console.log(name); // {who: null} ``` Because the inner control is constructed explicitly by the caller, the builder has no control over how it is created, and cannot exclude the `null`. | Methods ------- | group() | | --- | | Constructs a new `[FormGroup](formgroup)` instance. Accepts a single generic argument, which is an object containing all the keys and corresponding inner control types. `group<T extends {}>(controls: T, options?: AbstractControlOptions): FormGroup<{ [K in keyof T]: ɵElement<T[K], null>; }>` Parameters | | | | | --- | --- | --- | | `controls` | `T` | A collection of child controls. The key for each child is the name under which it is registered. | | `options` | `[AbstractControlOptions](abstractcontroloptions)` | Configuration options object for the `[FormGroup](formgroup)`. The object should have the `[AbstractControlOptions](abstractcontroloptions)` type and might contain the following fields:* `validators`: A synchronous validator function, or an array of validator functions. * `asyncValidators`: A single async validator or array of async validator functions. * `updateOn`: The event upon which the control should be updated (options: 'change' | 'blur' | submit'). Optional. Default is `undefined`. | Returns `[FormGroup](formgroup)<{ [K in keyof T]: ɵElement<T[K], null>; }>` | | Constructs a new `[FormGroup](formgroup)` instance. `group(controls: { [key: string]: any; }, options: { [key: string]: any; }): FormGroup` **Deprecated** This API is not typesafe and can result in issues with Closure Compiler renaming. Use the `[FormBuilder](formbuilder)#group` overload with `[AbstractControlOptions](abstractcontroloptions)` instead. Note that `[AbstractControlOptions](abstractcontroloptions)` expects `validators` and `asyncValidators` to be valid validators. If you have custom validators, make sure their validation function parameter is `[AbstractControl](abstractcontrol)` and not a sub-class, such as `[FormGroup](formgroup)`. These functions will be called with an object of type `[AbstractControl](abstractcontrol)` and that cannot be automatically downcast to a subclass, so TypeScript sees this as an error. For example, change the `(group: [FormGroup](formgroup)) => [ValidationErrors](validationerrors)|null` signature to be `(group: [AbstractControl](abstractcontrol)) => [ValidationErrors](validationerrors)|null`. Parameters | | | | | --- | --- | --- | | `controls` | `object` | A record of child controls. The key for each child is the name under which the control is registered. | | `options` | `object` | Configuration options object for the `[FormGroup](formgroup)`. The legacy configuration object consists of:* `validator`: A synchronous validator function, or an array of validator functions. * `asyncValidator`: A single async validator or array of async validator functions Note: the legacy format is deprecated and might be removed in one of the next major versions of Angular. | Returns `[FormGroup](formgroup)` | | record() | | --- | | Constructs a new `[FormRecord](formrecord)` instance. Accepts a single generic argument, which is an object containing all the keys and corresponding inner control types. | | `record<T>(controls: { [key: string]: T; }, options: AbstractControlOptions = null): FormRecord<ɵElement<T, null>>` Parameters | | | | | --- | --- | --- | | `controls` | `object` | A collection of child controls. The key for each child is the name under which it is registered. | | `options` | `[AbstractControlOptions](abstractcontroloptions)` | Configuration options object for the `[FormRecord](formrecord)`. The object should have the `[AbstractControlOptions](abstractcontroloptions)` type and might contain the following fields:* `validators`: A synchronous validator function, or an array of validator functions. * `asyncValidators`: A single async validator or array of async validator functions. * `updateOn`: The event upon which the control should be updated (options: 'change' | 'blur' | submit'). Optional. Default is `null`. | Returns `[FormRecord](formrecord)<ɵElement<T, null>>` | | control() | | --- | | Constructs a new `[FormControl](formcontrol)` with the given state, validators and options. Sets `{nonNullable: true}` in the options to get a non-nullable control. Otherwise, the control will be nullable. Accepts a single generic argument, which is the type of the control's value. | | 4 overloads... Show All Hide All Overload #1 `control<T>(formState: T | FormControlState<T>, opts: FormControlOptions & { initialValueIsDefault: true; }): FormControl<T>` **Deprecated** Use `nonNullable` instead. Parameters | | | | | --- | --- | --- | | `formState` | `T | [FormControlState](formcontrolstate)<T>` | | | `opts` | `[FormControlOptions](formcontroloptions) & { initialValueIsDefault: true; }` | | Returns `[FormControl](formcontrol)<T>` Overload #2 `control<T>(formState: T | FormControlState<T>, opts: FormControlOptions & { nonNullable: true; }): FormControl<T>` Parameters | | | | | --- | --- | --- | | `formState` | `T | [FormControlState](formcontrolstate)<T>` | | | `opts` | `[FormControlOptions](formcontroloptions) & { nonNullable: true; }` | | Returns `[FormControl](formcontrol)<T>` Overload #3 `control<T>(formState: T | FormControlState<T>, opts: FormControlOptions, asyncValidator: AsyncValidatorFn | AsyncValidatorFn[]): FormControl<T | null>` **Deprecated** When passing an `options` argument, the `asyncValidator` argument has no effect. Parameters | | | | | --- | --- | --- | | `formState` | `T | [FormControlState](formcontrolstate)<T>` | | | `opts` | `[FormControlOptions](formcontroloptions)` | | | `asyncValidator` | `[AsyncValidatorFn](asyncvalidatorfn) | [AsyncValidatorFn](asyncvalidatorfn)[]` | | Returns `[FormControl](formcontrol)<T | null>` Overload #4 `control<T>(formState: T | FormControlState<T>, validatorOrOpts?: ValidatorFn | FormControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]): FormControl<T | null>` Parameters | | | | | --- | --- | --- | | `formState` | `T | [FormControlState](formcontrolstate)<T>` | | | `validatorOrOpts` | `[ValidatorFn](validatorfn) | [FormControlOptions](formcontroloptions) | [ValidatorFn](validatorfn)[]` | Optional. Default is `undefined`. | | `asyncValidator` | `[AsyncValidatorFn](asyncvalidatorfn) | [AsyncValidatorFn](asyncvalidatorfn)[]` | Optional. Default is `undefined`. | Returns `[FormControl](formcontrol)<T | null>` | | Usage Notes Initialize a control as disabled The following example returns a control with an initial value in a disabled state. ``` import {Component, Inject} from '@angular/core'; import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms'; /* . . . */ @Component({ selector: 'app-disabled-form-control', template: ` <input [formControl]="control" placeholder="First"> ` }) export class DisabledFormControlComponent { control: FormControl; constructor(private fb: FormBuilder) { this.control = fb.control({value: 'my val', disabled: true}); } } ``` | | array() | | --- | | Constructs a new `[FormArray](formarray)` from the given array of configurations, validators and options. Accepts a single generic argument, which is the type of each control inside the array. | | `array<T>(controls: T[], validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]): FormArray<ɵElement<T, null>>` Parameters | | | | | --- | --- | --- | | `controls` | `T[]` | An array of child controls or control configs. Each child control is given an index when it is registered. | | `validatorOrOpts` | `[ValidatorFn](validatorfn) | [AbstractControlOptions](abstractcontroloptions) | [ValidatorFn](validatorfn)[]` | A synchronous validator function, or an array of such functions, or an `[AbstractControlOptions](abstractcontroloptions)` object that contains validation functions and a validation trigger. Optional. Default is `undefined`. | | `asyncValidator` | `[AsyncValidatorFn](asyncvalidatorfn) | [AsyncValidatorFn](asyncvalidatorfn)[]` | A single async validator or array of async validator functions. Optional. Default is `undefined`. | Returns `[FormArray](formarray)<ɵElement<T, null>>` | angular NgForm NgForm ====== `directive` Creates a top-level `[FormGroup](formgroup)` instance and binds it to a form to track aggregate form value and validation status. [See more...](ngform#description) Exported from ------------- * [``` FormsModule ```](formsmodule) Selectors --------- * `form*:not([ngNoForm])**:not([formGroup])*` * `[ng-form](ngform)` * `[[ngForm](ngform)]` Properties ---------- | Property | Description | | --- | --- | | `submitted: boolean` | Read-Only Returns whether the form submission has been triggered. | | `form: [FormGroup](formgroup)` | The `[FormGroup](formgroup)` instance created for this form. | | `@[Output](../core/output)()ngSubmit: [EventEmitter](../core/eventemitter)` | Event emitter for the "ngSubmit" event | | `@[Input](../core/input)('ngFormOptions')options: { updateOn?: FormHooks; }` | Tracks options for the `[NgForm](ngform)` instance. **updateOn**: Sets the default `updateOn` value for all child `NgModels` below it unless explicitly set by a child `[NgModel](ngmodel)` using `ngModelOptions`). Defaults to 'change'. Possible values: `'change'` | `'blur'` | `'submit'`. | | `formDirective: [Form](form)` | Read-Only The directive instance. | | `control: [FormGroup](formgroup)` | Read-Only The internal `[FormGroup](formgroup)` instance. | | `path: string[]` | Read-Only Returns an array representing the path to this group. Because this directive always lives at the top level of a form, it is always an empty array. | | `controls: { [key: string]: [AbstractControl](abstractcontrol); }` | Read-Only Returns a map of the controls in this group. | ### Inherited from `[ControlContainer](controlcontainer)` * `[name: string | number | null](controlcontainer#name)` * `[formDirective: Form | null](controlcontainer#formDirective)` * `[path: string[] | null](controlcontainer#path)` ### Inherited from `[AbstractControlDirective](abstractcontroldirective)` * `[abstract control: AbstractControl | null](abstractcontroldirective#control)` * `[value: any](abstractcontroldirective#value)` * `[valid: boolean | null](abstractcontroldirective#valid)` * `[invalid: boolean | null](abstractcontroldirective#invalid)` * `[pending: boolean | null](abstractcontroldirective#pending)` * `[disabled: boolean | null](abstractcontroldirective#disabled)` * `[enabled: boolean | null](abstractcontroldirective#enabled)` * `[errors: ValidationErrors | null](abstractcontroldirective#errors)` * `[pristine: boolean | null](abstractcontroldirective#pristine)` * `[dirty: boolean | null](abstractcontroldirective#dirty)` * `[touched: boolean | null](abstractcontroldirective#touched)` * `[status: string | null](abstractcontroldirective#status)` * `[untouched: boolean | null](abstractcontroldirective#untouched)` * `[statusChanges: Observable<any> | null](abstractcontroldirective#statusChanges)` * `[valueChanges: Observable<any> | null](abstractcontroldirective#valueChanges)` * `[path: string[] | null](abstractcontroldirective#path)` * `[validator: ValidatorFn | null](abstractcontroldirective#validator)` * `[asyncValidator: AsyncValidatorFn | null](abstractcontroldirective#asyncValidator)` Template variable references ---------------------------- | Identifier | Usage | | --- | --- | | `[ngForm](ngform)` | `#myTemplateVar="[ngForm](ngform)"` | Description ----------- As soon as you import the `[FormsModule](formsmodule)`, this directive becomes active by default on all `<form>` tags. You don't need to add a special selector. You optionally export the directive into a local template variable using `[ngForm](ngform)` as the key (ex: `#myForm="[ngForm](ngform)"`). This is optional, but useful. Many properties from the underlying `[FormGroup](formgroup)` instance are duplicated on the directive itself, so a reference to it gives you access to the aggregate value and validity status of the form, as well as user interaction properties like `dirty` and `touched`. To register child controls with the form, use `[NgModel](ngmodel)` with a `name` attribute. You may use `[NgModelGroup](ngmodelgroup)` to create sub-groups within the form. If necessary, listen to the directive's `ngSubmit` event to be notified when the user has triggered a form submission. The `ngSubmit` event emits the original form submission event. In template driven forms, all `<form>` tags are automatically tagged as `[NgForm](ngform)`. To import the `[FormsModule](formsmodule)` but skip its usage in some forms, for example, to use native HTML5 validation, add the `ngNoForm` and the `<form>` tags won't create an `[NgForm](ngform)` directive. In reactive forms, using `ngNoForm` is unnecessary because the `<form>` tags are inert. In that case, you would refrain from using the `formGroup` directive. ### Listening for form submission The following example shows how to capture the form values from the "ngSubmit" event. ``` import {Component} from '@angular/core'; import {NgForm} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate> <input name="first" ngModel required #first="ngModel"> <input name="last" ngModel> <button>Submit</button> </form> <p>First name value: {{ first.value }}</p> <p>First name valid: {{ first.valid }}</p> <p>Form value: {{ f.value | json }}</p> <p>Form valid: {{ f.valid }}</p> `, }) export class SimpleFormComp { onSubmit(f: NgForm) { console.log(f.value); // { first: '', last: '' } console.log(f.valid); // false } } ``` ### Setting the update options The following example shows you how to change the "updateOn" option from its default using ngFormOptions. ``` <form [ngFormOptions]="{updateOn: 'blur'}"> <input name="one" ngModel> <!-- this ngModel will update on blur --> </form> ``` ### Native DOM validation UI In order to prevent the native DOM form validation UI from interfering with Angular's form validation, Angular automatically adds the `novalidate` attribute on any `<form>` whenever `FormModule` or `ReactiveFormModule` are imported into the application. If you want to explicitly enable native DOM validation UI with Angular forms, you can add the `ngNativeValidate` attribute to the `<form>` element: ``` <form ngNativeValidate> ... </form> ``` Methods ------- | addControl() | | --- | | Method that sets up the control directive in this group, re-calculates its value and validity, and adds the instance to the internal list of directives. | | `addControl(dir: NgModel): void` Parameters | | | | | --- | --- | --- | | `dir` | `[NgModel](ngmodel)` | The `[NgModel](ngmodel)` directive instance. | Returns `void` | | getControl() | | --- | | Retrieves the `[FormControl](formcontrol)` instance from the provided `[NgModel](ngmodel)` directive. | | `getControl(dir: NgModel): FormControl` Parameters | | | | | --- | --- | --- | | `dir` | `[NgModel](ngmodel)` | The `[NgModel](ngmodel)` directive instance. | Returns `[FormControl](formcontrol)` | | removeControl() | | --- | | Removes the `[NgModel](ngmodel)` instance from the internal list of directives | | `removeControl(dir: NgModel): void` Parameters | | | | | --- | --- | --- | | `dir` | `[NgModel](ngmodel)` | The `[NgModel](ngmodel)` directive instance. | Returns `void` | | addFormGroup() | | --- | | Adds a new `[NgModelGroup](ngmodelgroup)` directive instance to the form. | | `addFormGroup(dir: NgModelGroup): void` Parameters | | | | | --- | --- | --- | | `dir` | `[NgModelGroup](ngmodelgroup)` | The `[NgModelGroup](ngmodelgroup)` directive instance. | Returns `void` | | removeFormGroup() | | --- | | Removes the `[NgModelGroup](ngmodelgroup)` directive instance from the form. | | `removeFormGroup(dir: NgModelGroup): void` Parameters | | | | | --- | --- | --- | | `dir` | `[NgModelGroup](ngmodelgroup)` | The `[NgModelGroup](ngmodelgroup)` directive instance. | Returns `void` | | getFormGroup() | | --- | | Retrieves the `[FormGroup](formgroup)` for a provided `[NgModelGroup](ngmodelgroup)` directive instance | | `getFormGroup(dir: NgModelGroup): FormGroup` Parameters | | | | | --- | --- | --- | | `dir` | `[NgModelGroup](ngmodelgroup)` | The `[NgModelGroup](ngmodelgroup)` directive instance. | Returns `[FormGroup](formgroup)` | | updateModel() | | --- | | Sets the new value for the provided `[NgControl](ngcontrol)` directive. | | `updateModel(dir: NgControl, value: any): void` Parameters | | | | | --- | --- | --- | | `dir` | `[NgControl](ngcontrol)` | The `[NgControl](ngcontrol)` directive instance. | | `value` | `any` | The new value for the directive's control. | Returns `void` | | setValue() | | --- | | Sets the value for this `[FormGroup](formgroup)`. | | `setValue(value: { [key: string]: any; }): void` Parameters | | | | | --- | --- | --- | | `value` | `object` | The new value | Returns `void` | | onSubmit() | | --- | | Method called when the "submit" event is triggered on the form. Triggers the `ngSubmit` emitter to emit the "submit" event as its payload. | | `onSubmit($event: Event): boolean` Parameters | | | | | --- | --- | --- | | `$event` | `[Event](../router/event)` | The "submit" event object | Returns `boolean` | | onReset() | | --- | | Method called when the "reset" event is triggered on the form. | | `onReset(): void` Parameters There are no parameters. Returns `void` | | resetForm() | | --- | | Resets the form to an initial value and resets its submitted status. | | `resetForm(value: any = undefined): void` Parameters | | | | | --- | --- | --- | | `value` | `any` | The new value for the form. Optional. Default is `undefined`. | Returns `void` | ### Inherited from `[AbstractControlDirective](abstractcontroldirective)` * `[reset(value: any = undefined): void](abstractcontroldirective#reset)` * `[hasError(errorCode: string, path?: string | (string | number)[]): boolean](abstractcontroldirective#hasError)` * `[getError(errorCode: string, path?: string | (string | number)[]): any](abstractcontroldirective#getError)`
programming_docs
angular PatternValidator PatternValidator ================ `directive` A directive that adds regex pattern validation to controls marked with the `[pattern](patternvalidator)` attribute. The regex must match the entire control value. The directive is provided with the `[NG\_VALIDATORS](ng_validators)` multi-provider list. See also -------- * [Form Validation](../../guide/form-validation) Exported from ------------- * [``` ReactiveFormsModule ```](reactiveformsmodule) * [``` FormsModule ```](formsmodule) Selectors --------- * `[[pattern](patternvalidator)][[formControlName](formcontrolname)]` * `[[pattern](patternvalidator)][formControl]` * `[[pattern](patternvalidator)][[ngModel](ngmodel)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)()[pattern](patternvalidator): string | RegExp` | Tracks changes to the pattern bound to this directive. | Description ----------- ### Adding a pattern validator The following example shows how to add a pattern validator to an input attached to an ngModel binding. ``` <input name="firstName" ngModel pattern="[a-zA-Z ]*"> ``` angular FormControl FormControl =========== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Tracks the value and validation status of an individual form control. [See more...](formcontrol#description) ``` class FormControl<TValue = any> extends AbstractControl<TValue> { new (): FormControl<any> defaultValue: TValue setValue(value: TValue, options?: { onlySelf?: boolean; emitEvent?: boolean; emitModelToViewChange?: boolean; emitViewToModelChange?: boolean; }): void patchValue(value: TValue, options?: { onlySelf?: boolean; emitEvent?: boolean; emitModelToViewChange?: boolean; emitViewToModelChange?: boolean; }): void reset(formState?: TValue | FormControlState<TValue>, options?: { onlySelf?: boolean; emitEvent?: boolean; }): void getRawValue(): TValue registerOnChange(fn: Function): void registerOnDisabledChange(fn: (isDisabled: boolean) => void): void // inherited from forms/AbstractControl constructor(validators: ValidatorFn | ValidatorFn[], asyncValidators: AsyncValidatorFn | AsyncValidatorFn[]) value: TValue validator: ValidatorFn | null asyncValidator: AsyncValidatorFn | null parent: FormGroup | FormArray | null status: FormControlStatus valid: boolean invalid: boolean pending: boolean disabled: boolean enabled: boolean errors: ValidationErrors | null pristine: boolean dirty: boolean touched: boolean untouched: boolean valueChanges: Observable<TValue> statusChanges: Observable<FormControlStatus> updateOn: FormHooks root: AbstractControl setValidators(validators: ValidatorFn | ValidatorFn[]): void setAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void addValidators(validators: ValidatorFn | ValidatorFn[]): void addAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void removeValidators(validators: ValidatorFn | ValidatorFn[]): void removeAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void hasValidator(validator: ValidatorFn): boolean hasAsyncValidator(validator: AsyncValidatorFn): boolean clearValidators(): void clearAsyncValidators(): void markAsTouched(opts: { onlySelf?: boolean; } = {}): void markAllAsTouched(): void markAsUntouched(opts: { onlySelf?: boolean; } = {}): void markAsDirty(opts: { onlySelf?: boolean; } = {}): void markAsPristine(opts: { onlySelf?: boolean; } = {}): void markAsPending(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void disable(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void enable(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void setParent(parent: FormGroup<any> | FormArray<any>): void abstract setValue(value: TRawValue, options?: Object): void abstract patchValue(value: TValue, options?: Object): void abstract reset(value?: TValue, options?: Object): void getRawValue(): any updateValueAndValidity(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void setErrors(errors: ValidationErrors, opts: { emitEvent?: boolean; } = {}): void get<P extends string | ((string | number)[])>(path: P): AbstractControl<ɵGetProperty<TRawValue, P>> | null getError(errorCode: string, path?: string | (string | number)[]): any hasError(errorCode: string, path?: string | (string | number)[]): boolean } ``` See also -------- * `[AbstractControl](abstractcontrol)` * [Reactive Forms Guide](../../guide/reactive-forms) * [Usage Notes](formcontrol#usage-notes) Description ----------- This is one of the four fundamental building blocks of Angular forms, along with `[FormGroup](formgroup)`, `[FormArray](formarray)` and `[FormRecord](formrecord)`. It extends the `[AbstractControl](abstractcontrol)` class that implements most of the base functionality for accessing the value, validation status, user interactions and events. `[FormControl](formcontrol)` takes a single generic argument, which describes the type of its value. This argument always implicitly includes `null` because the control can be reset. To change this behavior, set `nonNullable` or see the usage notes below. See [usage examples below](formcontrol#usage-notes). Further information is available in the [Usage Notes...](formcontrol#usage-notes) Constructor ----------- | *construct signature* | | --- | | Construct a FormControl with no initial value or validators. | | 4 overloads... Show All Hide All Overload #1 Creates a new `[FormControl](formcontrol)` instance. `new <T = any>(value: T | FormControlState<T>, opts: FormControlOptions & { nonNullable: true; }): FormControl<T>` Parameters | | | | | --- | --- | --- | | `value` | `T | [FormControlState](formcontrolstate)<T>` | | | `opts` | `[FormControlOptions](formcontroloptions) & { nonNullable: true; }` | | Returns `[FormControl](formcontrol)<T>` Overload #2 `new <T = any>(value: T | FormControlState<T>, opts: FormControlOptions & { initialValueIsDefault: true; }): FormControl<T>` **Deprecated** Use `nonNullable` instead. Parameters | | | | | --- | --- | --- | | `value` | `T | [FormControlState](formcontrolstate)<T>` | | | `opts` | `[FormControlOptions](formcontroloptions) & { initialValueIsDefault: true; }` | | Returns `[FormControl](formcontrol)<T>` Overload #3 `new <T = any>(value: T | FormControlState<T>, opts: FormControlOptions, asyncValidator: AsyncValidatorFn | AsyncValidatorFn[]): FormControl<T | null>` **Deprecated** When passing an `options` argument, the `asyncValidator` argument has no effect. Parameters | | | | | --- | --- | --- | | `value` | `T | [FormControlState](formcontrolstate)<T>` | | | `opts` | `[FormControlOptions](formcontroloptions)` | | | `asyncValidator` | `[AsyncValidatorFn](asyncvalidatorfn) | [AsyncValidatorFn](asyncvalidatorfn)[]` | | Returns `[FormControl](formcontrol)<T | null>` Overload #4 `new <T = any>(value: T | FormControlState<T>, validatorOrOpts?: ValidatorFn | FormControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]): FormControl<T | null>` Parameters | | | | | --- | --- | --- | | `value` | `T | [FormControlState](formcontrolstate)<T>` | | | `validatorOrOpts` | `[ValidatorFn](validatorfn) | [FormControlOptions](formcontroloptions) | [ValidatorFn](validatorfn)[]` | Optional. Default is `undefined`. | | `asyncValidator` | `[AsyncValidatorFn](asyncvalidatorfn) | [AsyncValidatorFn](asyncvalidatorfn)[]` | Optional. Default is `undefined`. | Returns `[FormControl](formcontrol)<T | null>` | Properties ---------- | Property | Description | | --- | --- | | `defaultValue: TValue` | Read-Only The default value of this FormControl, used whenever the control is reset without an explicit value. See [`FormControlOptions`](formcontroloptions#nonNullable) for more information on configuring a default value. | Methods ------- | setValue() | | --- | | Sets a new value for the form control. | | `setValue(value: TValue, options?: { onlySelf?: boolean; emitEvent?: boolean; emitModelToViewChange?: boolean; emitViewToModelChange?: boolean; }): void` Parameters | | | | | --- | --- | --- | | `value` | `TValue` | The new value for the control. | | `options` | `object` | Configuration options that determine how the control propagates changes and emits events when the value changes. The configuration options are passed to the [updateValueAndValidity](abstractcontrol#updateValueAndValidity) method.* `onlySelf`: When true, each change only affects this control, and not its parent. Default is false. * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and `valueChanges` observables emit events with the latest status and value when the control value is updated. When false, no events are emitted. * `emitModelToViewChange`: When true or not supplied (the default), each change triggers an `onChange` event to update the view. * `emitViewToModelChange`: When true or not supplied (the default), each change triggers an `ngModelChange` event to update the model. Optional. Default is `undefined`. | Returns `void` | | patchValue() | | --- | | Patches the value of a control. See also:* `setValue` for options | | `patchValue(value: TValue, options?: { onlySelf?: boolean; emitEvent?: boolean; emitModelToViewChange?: boolean; emitViewToModelChange?: boolean; }): void` Parameters | | | | | --- | --- | --- | | `value` | `TValue` | | | `options` | `object` | Optional. Default is `undefined`. | Returns `void` | | This function is functionally the same as [setValue](formcontrol#setValue) at this level. It exists for symmetry with [patchValue](formgroup#patchValue) on `FormGroups` and `FormArrays`, where it does behave differently. | | reset() | | --- | | Resets the form control, marking it `pristine` and `untouched`, and resetting the value. The new value will be the provided value (if passed), `null`, or the initial value if `nonNullable` was set in the constructor via [`FormControlOptions`](formcontroloptions). | | `reset(formState?: TValue | FormControlState<TValue>, options?: { onlySelf?: boolean; emitEvent?: boolean; }): void` Parameters | | | | | --- | --- | --- | | `formState` | `TValue | [FormControlState](formcontrolstate)<TValue>` | Resets the control with an initial value, or an object that defines the initial value and disabled state. Optional. Default is `undefined`. | | `options` | `object` | Configuration options that determine how the control propagates changes and emits events after the value changes.* `onlySelf`: When true, each change only affects this control, and not its parent. Default is false. * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and `valueChanges` observables emit events with the latest status and value when the control is reset. When false, no events are emitted. Optional. Default is `undefined`. | Returns `void` | | ``` // By default, the control will reset to null. const dog = new FormControl('spot'); dog.reset(); // dog.value is null // If this flag is set, the control will instead reset to the initial value. const cat = new FormControl('tabby', {nonNullable: true}); cat.reset(); // cat.value is "tabby" // A value passed to reset always takes precedence. const fish = new FormControl('finn', {nonNullable: true}); fish.reset('bubble'); // fish.value is "bubble" ``` | | getRawValue() | | --- | | For a simple FormControl, the raw value is equivalent to the value. | | `getRawValue(): TValue` Parameters There are no parameters. Returns `TValue` | | registerOnChange() | | --- | | Register a listener for change events. | | `registerOnChange(fn: Function): void` Parameters | | | | | --- | --- | --- | | `fn` | `Function` | The method that is called when the value changes | Returns `void` | | registerOnDisabledChange() | | --- | | Register a listener for disabled events. | | `registerOnDisabledChange(fn: (isDisabled: boolean) => void): void` Parameters | | | | | --- | --- | --- | | `fn` | `(isDisabled: boolean) => void` | The method that is called when the disabled status changes. | Returns `void` | Usage notes ----------- ### Initializing Form Controls Instantiate a `[FormControl](formcontrol)`, with an initial value. ``` const control = new FormControl('some value'); console.log(control.value); // 'some value' ``` The following example initializes the control with a form state object. The `value` and `disabled` keys are required in this case. ``` const control = new FormControl({ value: 'n/a', disabled: true }); console.log(control.value); // 'n/a' console.log(control.status); // 'DISABLED' ``` The following example initializes the control with a synchronous validator. ``` const control = new FormControl('', Validators.required); console.log(control.value); // '' console.log(control.status); // 'INVALID' ``` The following example initializes the control using an options object. ``` const control = new FormControl('', { validators: Validators.required, asyncValidators: myAsyncValidator }); ``` ### The single type argument `[FormControl](formcontrol)` accepts a generic argument, which describes the type of its value. In most cases, this argument will be inferred. If you are initializing the control to `null`, or you otherwise wish to provide a wider type, you may specify the argument explicitly: ``` let fc = new FormControl<string|null>(null); fc.setValue('foo'); ``` You might notice that `null` is always added to the type of the control. This is because the control will become `null` if you call `reset`. You can change this behavior by setting `{nonNullable: true}`. ### Configure the control to update on a blur event Set the `updateOn` option to `'blur'` to update on the blur `event`. ``` const control = new FormControl('', { updateOn: 'blur' }); ``` ### Configure the control to update on a submit event Set the `updateOn` option to `'submit'` to update on a submit `event`. ``` const control = new FormControl('', { updateOn: 'submit' }); ``` ### Reset the control back to a specific value You reset to a specific form state by passing through a standalone value or a form state object that contains both a value and a disabled state (these are the only two properties that cannot be calculated). ``` const control = new FormControl('Nancy'); console.log(control.value); // 'Nancy' control.reset('Drew'); console.log(control.value); // 'Drew' ``` ### Reset the control to its initial value If you wish to always reset the control to its initial value (instead of null), you can pass the `nonNullable` option: ``` const control = new FormControl('Nancy', {nonNullable: true}); console.log(control.value); // 'Nancy' control.reset(); console.log(control.value); // 'Nancy' ``` ### Reset the control back to an initial value and disabled ``` const control = new FormControl('Nancy'); console.log(control.value); // 'Nancy' console.log(control.status); // 'VALID' control.reset({ value: 'Drew', disabled: true }); console.log(control.value); // 'Drew' console.log(control.status); // 'DISABLED' ``` angular ControlConfig ControlConfig ============= `type-alias` ControlConfig is a tuple containing a value of type T, plus optional validators and async validators. ``` type ControlConfig<T> = [ T | FormControlState<T>, (ValidatorFn | (ValidatorFn[]))?, (AsyncValidatorFn | AsyncValidatorFn[])? ]; ``` angular isFormGroup isFormGroup =========== `const` Asserts that the given control is an instance of `[FormGroup](formgroup)` ### `const isFormGroup: (control: unknown) => control is FormGroup<any>;` angular EmailValidator EmailValidator ============== `directive` A directive that adds the `[email](emailvalidator)` validator to controls marked with the `[email](emailvalidator)` attribute. The directive is provided with the `[NG\_VALIDATORS](ng_validators)` multi-provider list. [See more...](emailvalidator#description) See also -------- * [Form Validation](../../guide/form-validation) Exported from ------------- * [``` FormsModule ```](formsmodule) * [``` ReactiveFormsModule ```](reactiveformsmodule) Selectors --------- * `[[email](emailvalidator)][[formControlName](formcontrolname)]` * `[[email](emailvalidator)][formControl]` * `[[email](emailvalidator)][[ngModel](ngmodel)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)()[email](emailvalidator): boolean | string` | Tracks changes to the email attribute bound to this directive. | Description ----------- The email validation is based on the WHATWG HTML specification with some enhancements to incorporate more RFC rules. More information can be found on the [Validators.email page](validators#email). ### Adding an email validator The following example shows how to add an email validator to an input attached to an ngModel binding. ``` <input type="email" name="email" ngModel email> <input type="email" name="email" ngModel email="true"> <input type="email" name="email" ngModel [email]="true"> ``` angular AbstractControlOptions AbstractControlOptions ====================== `interface` Interface for options provided to an `[AbstractControl](abstractcontrol)`. ``` interface AbstractControlOptions { validators?: ValidatorFn | ValidatorFn[] | null asyncValidators?: AsyncValidatorFn | AsyncValidatorFn[] | null updateOn?: 'change' | 'blur' | 'submit' } ``` Child interfaces ---------------- * `[FormControlOptions](formcontroloptions)` Properties ---------- | Property | Description | | --- | --- | | `validators?: [ValidatorFn](validatorfn) | [ValidatorFn](validatorfn)[] | null` | The list of validators applied to a control. | | `asyncValidators?: [AsyncValidatorFn](asyncvalidatorfn) | [AsyncValidatorFn](asyncvalidatorfn)[] | null` | The list of async validators applied to control. | | `updateOn?: 'change' | 'blur' | 'submit'` | The event name for control to update upon. | angular AsyncValidator AsyncValidator ============== `interface` An interface implemented by classes that perform asynchronous validation. ``` interface AsyncValidator extends Validator { validate(control: AbstractControl<any, any>): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> // inherited from forms/Validator validate(control: AbstractControl<any, any>): ValidationErrors | null registerOnValidatorChange(fn: () => void)?: void } ``` Methods ------- | validate() | | --- | | Method that performs async validation against the provided control. | | `validate(control: AbstractControl<any, any>): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>` Parameters | | | | | --- | --- | --- | | `control` | `[AbstractControl](abstractcontrol)<any, any>` | The control to validate against. | Returns `Promise<[ValidationErrors](validationerrors) | null> | Observable<[ValidationErrors](validationerrors) | null>`: A promise or observable that resolves a map of validation errors if validation fails, otherwise null. | Usage notes ----------- ### Provide a custom async validator directive The following example implements the `[AsyncValidator](asyncvalidator)` interface to create an async validator directive with a custom error key. ``` import { of } from 'rxjs'; @Directive({ selector: '[customAsyncValidator]', providers: [{provide: NG_ASYNC_VALIDATORS, useExisting: CustomAsyncValidatorDirective, multi: true}] }) class CustomAsyncValidatorDirective implements AsyncValidator { validate(control: AbstractControl): Observable<ValidationErrors|null> { return of({'custom': true}); } } ``` angular Validators Validators ========== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Provides a set of built-in validators that can be used by form controls. [See more...](validators#description) ``` class Validators { static min(min: number): ValidatorFn static max(max: number): ValidatorFn static required(control: AbstractControl<any, any>): ValidationErrors | null static requiredTrue(control: AbstractControl<any, any>): ValidationErrors | null static email(control: AbstractControl<any, any>): ValidationErrors | null static minLength(minLength: number): ValidatorFn static maxLength(maxLength: number): ValidatorFn static pattern(pattern: string | RegExp): ValidatorFn static nullValidator(control: AbstractControl<any, any>): ValidationErrors | null static compose(validators: ValidatorFn[]): ValidatorFn | null static composeAsync(validators: AsyncValidatorFn[]): AsyncValidatorFn | null } ``` See also -------- * [Form Validation](../../guide/form-validation) Description ----------- A validator is a function that processes a `[FormControl](formcontrol)` or collection of controls and returns an error map or null. A null map means that validation has passed. Static methods -------------- | min() | | --- | | Validator that requires the control's value to be greater than or equal to the provided number. See also:* `updateValueAndValidity()` | | `static min(min: number): ValidatorFn` Parameters | | | | | --- | --- | --- | | `[min](minvalidator)` | `number` | | Returns `[ValidatorFn](validatorfn)`: A validator function that returns an error map with the `[min](minvalidator)` property if the validation check fails, otherwise `null`. | | Usage Notes Validate against a minimum of 3 ``` const control = new FormControl(2, Validators.min(3)); console.log(control.errors); // {min: {min: 3, actual: 2}} ``` | | max() | | --- | | Validator that requires the control's value to be less than or equal to the provided number. See also:* `updateValueAndValidity()` | | `static max(max: number): ValidatorFn` Parameters | | | | | --- | --- | --- | | `[max](maxvalidator)` | `number` | | Returns `[ValidatorFn](validatorfn)`: A validator function that returns an error map with the `[max](maxvalidator)` property if the validation check fails, otherwise `null`. | | Usage Notes Validate against a maximum of 15 ``` const control = new FormControl(16, Validators.max(15)); console.log(control.errors); // {max: {max: 15, actual: 16}} ``` | | required() | | --- | | Validator that requires the control have a non-empty value. See also:* `updateValueAndValidity()` | | `static required(control: AbstractControl<any, any>): ValidationErrors | null` Parameters | | | | | --- | --- | --- | | `control` | `[AbstractControl](abstractcontrol)<any, any>` | | Returns `[ValidationErrors](validationerrors) | null`: An error map with the `required` property if the validation check fails, otherwise `null`. | | Usage Notes Validate that the field is non-empty ``` const control = new FormControl('', Validators.required); console.log(control.errors); // {required: true} ``` | | requiredTrue() | | --- | | Validator that requires the control's value be true. This validator is commonly used for required checkboxes. See also:* `updateValueAndValidity()` | | `static requiredTrue(control: AbstractControl<any, any>): ValidationErrors | null` Parameters | | | | | --- | --- | --- | | `control` | `[AbstractControl](abstractcontrol)<any, any>` | | Returns `[ValidationErrors](validationerrors) | null`: An error map that contains the `required` property set to `true` if the validation check fails, otherwise `null`. | | Usage Notes Validate that the field value is true ``` const control = new FormControl('some value', Validators.requiredTrue); console.log(control.errors); // {required: true} ``` | | email() | | --- | | Validator that requires the control's value pass an email validation test. See also:* `updateValueAndValidity()` | | `static email(control: AbstractControl<any, any>): ValidationErrors | null` Parameters | | | | | --- | --- | --- | | `control` | `[AbstractControl](abstractcontrol)<any, any>` | | Returns `[ValidationErrors](validationerrors) | null`: An error map with the `[email](emailvalidator)` property if the validation check fails, otherwise `null`. | | Tests the value using a [regular expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) pattern suitable for common use cases. The pattern is based on the definition of a valid email address in the [WHATWG HTML specification](https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address) with some enhancements to incorporate more RFC rules (such as rules related to domain names and the lengths of different parts of the address). The differences from the WHATWG version include:* Disallow `local-part` (the part before the `@` symbol) to begin or end with a period (`.`). * Disallow `local-part` to be longer than 64 characters. * Disallow the whole address to be longer than 254 characters. If this pattern does not satisfy your business needs, you can use `[Validators.pattern()](validators#pattern)` to validate the value against a different pattern. | | Usage Notes Validate that the field matches a valid email pattern ``` const control = new FormControl('bad@', Validators.email); console.log(control.errors); // {email: true} ``` | | minLength() | | --- | | Validator that requires the length of the control's value to be greater than or equal to the provided minimum length. This validator is also provided by default if you use the the HTML5 `[minlength](minlengthvalidator)` attribute. Note that the `minLength` validator is intended to be used only for types that have a numeric `length` property, such as strings or arrays. The `minLength` validator logic is also not invoked for values when their `length` property is 0 (for example in case of an empty string or an empty array), to support optional controls. You can use the standard `required` validator if empty values should not be considered valid. See also:* `updateValueAndValidity()` | | `static minLength(minLength: number): ValidatorFn` Parameters | | | | | --- | --- | --- | | `minLength` | `number` | | Returns `[ValidatorFn](validatorfn)`: A validator function that returns an error map with the `[minlength](minlengthvalidator)` property if the validation check fails, otherwise `null`. | | Usage Notes Validate that the field has a minimum of 3 characters ``` const control = new FormControl('ng', Validators.minLength(3)); console.log(control.errors); // {minlength: {requiredLength: 3, actualLength: 2}} ``` ``` <input minlength="5"> ``` | | maxLength() | | --- | | Validator that requires the length of the control's value to be less than or equal to the provided maximum length. This validator is also provided by default if you use the the HTML5 `[maxlength](maxlengthvalidator)` attribute. Note that the `maxLength` validator is intended to be used only for types that have a numeric `length` property, such as strings or arrays. See also:* `updateValueAndValidity()` | | `static maxLength(maxLength: number): ValidatorFn` Parameters | | | | | --- | --- | --- | | `maxLength` | `number` | | Returns `[ValidatorFn](validatorfn)`: A validator function that returns an error map with the `[maxlength](maxlengthvalidator)` property if the validation check fails, otherwise `null`. | | Usage Notes Validate that the field has maximum of 5 characters ``` const control = new FormControl('Angular', Validators.maxLength(5)); console.log(control.errors); // {maxlength: {requiredLength: 5, actualLength: 7}} ``` ``` <input maxlength="5"> ``` | | pattern() | | --- | | Validator that requires the control's value to match a regex pattern. This validator is also provided by default if you use the HTML5 `[pattern](patternvalidator)` attribute. See also:* `updateValueAndValidity()` | | `static pattern(pattern: string | RegExp): ValidatorFn` Parameters | | | | | --- | --- | --- | | `[pattern](patternvalidator)` | `string | RegExp` | A regular expression to be used as is to test the values, or a string. If a string is passed, the `^` character is prepended and the `$` character is appended to the provided string (if not already present), and the resulting regular expression is used to test the values. | Returns `[ValidatorFn](validatorfn)`: A validator function that returns an error map with the `[pattern](patternvalidator)` property if the validation check fails, otherwise `null`. | | Usage Notes Validate that the field only contains letters or spaces ``` const control = new FormControl('1', Validators.pattern('[a-zA-Z ]*')); console.log(control.errors); // {pattern: {requiredPattern: '^[a-zA-Z ]*$', actualValue: '1'}} ``` ``` <input pattern="[a-zA-Z ]*"> ``` Pattern matching with the global or sticky flag `RegExp` objects created with the `g` or `y` flags that are passed into `Validators.pattern` can produce different results on the same input when validations are run consecutively. This is due to how the behavior of `RegExp.prototype.test` is specified in [ECMA-262](https://tc39.es/ecma262/#sec-regexpbuiltinexec) (`RegExp` preserves the index of the last match when the global or sticky flag is used). Due to this behavior, it is recommended that when using `Validators.pattern` you **do not** pass in a `RegExp` object with either the global or sticky flag enabled. ``` // Not recommended (since the `g` flag is used) const controlOne = new FormControl('1', Validators.pattern(/foo/g)); // Good const controlTwo = new FormControl('1', Validators.pattern(/foo/)); ``` | | nullValidator() | | --- | | Validator that performs no operation. See also:* `updateValueAndValidity()` | | `static nullValidator(control: AbstractControl<any, any>): ValidationErrors | null` Parameters | | | | | --- | --- | --- | | `control` | `[AbstractControl](abstractcontrol)<any, any>` | | Returns `[ValidationErrors](validationerrors) | null` | | compose() | | --- | | Compose multiple validators into a single function that returns the union of the individual error maps for the provided control. `static compose(validators: null): null` Parameters | | | | | --- | --- | --- | | `validators` | `null` | | Returns `null`: A validator function that returns an error map with the merged error maps of the validators if the validation check fails, otherwise `null`. | | `static compose(validators: ValidatorFn[]): ValidatorFn | null` Parameters | | | | | --- | --- | --- | | `validators` | `[ValidatorFn](validatorfn)[]` | | Returns `[ValidatorFn](validatorfn) | null` | | composeAsync() | | --- | | Compose multiple async validators into a single function that returns the union of the individual error objects for the provided control. See also:* `updateValueAndValidity()` | | `static composeAsync(validators: AsyncValidatorFn[]): AsyncValidatorFn | null` Parameters | | | | | --- | --- | --- | | `validators` | `[AsyncValidatorFn](asyncvalidatorfn)[]` | | Returns `[AsyncValidatorFn](asyncvalidatorfn) | null`: A validator function that returns an error map with the merged error objects of the async validators if the validation check fails, otherwise `null`. |
programming_docs
angular MaxLengthValidator MaxLengthValidator ================== `directive` A directive that adds max length validation to controls marked with the `[maxlength](maxlengthvalidator)` attribute. The directive is provided with the `[NG\_VALIDATORS](ng_validators)` multi-provider list. See also -------- * [Form Validation](../../guide/form-validation) Exported from ------------- * [``` ReactiveFormsModule ```](reactiveformsmodule) * [``` FormsModule ```](formsmodule) Selectors --------- * `[[maxlength](maxlengthvalidator)][[formControlName](formcontrolname)]` * `[[maxlength](maxlengthvalidator)][formControl]` * `[[maxlength](maxlengthvalidator)][[ngModel](ngmodel)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)()[maxlength](maxlengthvalidator): string | number | null` | Tracks changes to the minimum length bound to this directive. | Description ----------- ### Adding a maximum length validator The following example shows how to add a maximum length validator to an input attached to an ngModel binding. ``` <input name="firstName" ngModel maxlength="25"> ``` angular FormGroup FormGroup ========= `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Tracks the value and validity state of a group of `[FormControl](formcontrol)` instances. [See more...](formgroup#description) ``` class FormGroup<TControl extends { [K in keyof TControl]: AbstractControl<any>; } = any> extends AbstractControl<ɵTypedOrUntyped<TControl, ɵFormGroupValue<TControl>, any>, ɵTypedOrUntyped<TControl, ɵFormGroupRawValue<TControl>, any>> { constructor(controls: TControl, validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]) controls: ɵTypedOrUntyped<TControl, TControl, {...} registerControl<K extends string & keyof TControl>(name: K, control: TControl[K]): TControl[K] addControl<K extends string & keyof TControl>(name: K, control: Required<TControl>[K], options: { emitEvent?: boolean; } = {}): void removeControl(name: string, options: { emitEvent?: boolean; } = {}): void setControl<K extends string & keyof TControl>(name: K, control: TControl[K], options: { emitEvent?: boolean; } = {}): void contains<K extends string & keyof TControl>(controlName: K): boolean setValue(value: ɵIsAny<TControl, { [key: string]: any; }, { [K in keyof TControl]: ɵRawValue<TControl[K]>; }>, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void patchValue(value: ɵIsAny<TControl, { [key: string]: any; }, Partial<{ [K in keyof TControl]: ɵValue<TControl[K]>; }>>, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void reset(value: ɵIsAny<TControl, any, ɵIsAny<TControl, { [key: string]: any; }, Partial<{ [K in keyof TControl]: ɵValue<TControl[K]>; }>>> = {} as unknown as ɵFormGroupValue<TControl>, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void getRawValue(): ɵTypedOrUntyped<TControl, ɵFormGroupRawValue<TControl>, any> // inherited from forms/AbstractControl constructor(validators: ValidatorFn | ValidatorFn[], asyncValidators: AsyncValidatorFn | AsyncValidatorFn[]) value: TValue validator: ValidatorFn | null asyncValidator: AsyncValidatorFn | null parent: FormGroup | FormArray | null status: FormControlStatus valid: boolean invalid: boolean pending: boolean disabled: boolean enabled: boolean errors: ValidationErrors | null pristine: boolean dirty: boolean touched: boolean untouched: boolean valueChanges: Observable<TValue> statusChanges: Observable<FormControlStatus> updateOn: FormHooks root: AbstractControl setValidators(validators: ValidatorFn | ValidatorFn[]): void setAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void addValidators(validators: ValidatorFn | ValidatorFn[]): void addAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void removeValidators(validators: ValidatorFn | ValidatorFn[]): void removeAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void hasValidator(validator: ValidatorFn): boolean hasAsyncValidator(validator: AsyncValidatorFn): boolean clearValidators(): void clearAsyncValidators(): void markAsTouched(opts: { onlySelf?: boolean; } = {}): void markAllAsTouched(): void markAsUntouched(opts: { onlySelf?: boolean; } = {}): void markAsDirty(opts: { onlySelf?: boolean; } = {}): void markAsPristine(opts: { onlySelf?: boolean; } = {}): void markAsPending(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void disable(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void enable(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void setParent(parent: FormGroup<any> | FormArray<any>): void abstract setValue(value: TRawValue, options?: Object): void abstract patchValue(value: TValue, options?: Object): void abstract reset(value?: TValue, options?: Object): void getRawValue(): any updateValueAndValidity(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void setErrors(errors: ValidationErrors, opts: { emitEvent?: boolean; } = {}): void get<P extends string | ((string | number)[])>(path: P): AbstractControl<ɵGetProperty<TRawValue, P>> | null getError(errorCode: string, path?: string | (string | number)[]): any hasError(errorCode: string, path?: string | (string | number)[]): boolean } ``` Subclasses ---------- * `[FormRecord](formrecord)` Description ----------- A `[FormGroup](formgroup)` aggregates the values of each child `[FormControl](formcontrol)` into one object, with each control name as the key. It calculates its status by reducing the status values of its children. For example, if one of the controls in a group is invalid, the entire group becomes invalid. `[FormGroup](formgroup)` is one of the four fundamental building blocks used to define forms in Angular, along with `[FormControl](formcontrol)`, `[FormArray](formarray)`, and `[FormRecord](formrecord)`. When instantiating a `[FormGroup](formgroup)`, pass in a collection of child controls as the first argument. The key for each child registers the name for the control. `[FormGroup](formgroup)` is intended for use cases where the keys are known ahead of time. If you need to dynamically add and remove controls, use [`FormRecord`](formrecord) instead. `[FormGroup](formgroup)` accepts an optional type parameter `TControl`, which is an object type with inner control types as values. Further information is available in the [Usage Notes...](formgroup#usage-notes) Constructor ----------- | | | --- | | Creates a new `[FormGroup](formgroup)` instance. This class is "final" and should not be extended. See the [public API notes](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes). | | `constructor(controls: TControl, validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[])` Parameters | | | | | --- | --- | --- | | `controls` | `TControl` | A collection of child controls. The key for each child is the name under which it is registered. | | `validatorOrOpts` | `[ValidatorFn](validatorfn) | [AbstractControlOptions](abstractcontroloptions) | [ValidatorFn](validatorfn)[]` | A synchronous validator function, or an array of such functions, or an `[AbstractControlOptions](abstractcontroloptions)` object that contains validation functions and a validation trigger. Optional. Default is `undefined`. | | `asyncValidator` | `[AsyncValidatorFn](asyncvalidatorfn) | [AsyncValidatorFn](asyncvalidatorfn)[]` | A single async validator or array of async validator functions Optional. Default is `undefined`. | | Properties ---------- | Property | Description | | --- | --- | | `controls: ɵTypedOrUntyped<TControl, TControl, { [key: string]: [AbstractControl](abstractcontrol)<any>; }>` | | Methods ------- | registerControl() | | --- | | Registers a control with the group's list of controls. In a strongly-typed group, the control must be in the group's type (possibly as an optional key). `registerControl<K extends string & keyof TControl>(name: K, control: TControl[K]): TControl[K]` Parameters | | | | | --- | --- | --- | | `name` | `K` | The control name to register in the collection | | `control` | `TControl[K]` | Provides the control for the given name | Returns `TControl[K]` | | `registerControl(name: string, control: AbstractControl<any, any>): AbstractControl<any>` Parameters | | | | | --- | --- | --- | | `name` | `string` | | | `control` | `[AbstractControl](abstractcontrol)<any, any>` | | Returns `[AbstractControl](abstractcontrol)<any>` | | This method does not update the value or validity of the control. Use [addControl](formgroup#addControl) instead. | | addControl() | | --- | | Add a control to this group. In a strongly-typed group, the control must be in the group's type (possibly as an optional key). `addControl(name: string, control: AbstractControl<any, any>, options?: { emitEvent?: boolean; }): void` Parameters | | | | | --- | --- | --- | | `name` | `string` | The control name to add to the collection | | `control` | `[AbstractControl](abstractcontrol)<any, any>` | Provides the control for the given name | | `options` | `object` | Specifies whether this FormGroup instance should emit events after a new control is added.* `emitEvent`: When true or not supplied (the default), both the `statusChanges` and `valueChanges` observables emit events with the latest status and value when the control is added. When false, no events are emitted. Optional. Default is `undefined`. | Returns `void` | | `addControl<K extends string & keyof TControl>(name: K, control: Required<TControl>[K], options?: { emitEvent?: boolean; }): void` Parameters | | | | | --- | --- | --- | | `name` | `K` | | | `control` | `Required<TControl>[K]` | | | `options` | `object` | Optional. Default is `undefined`. | Returns `void` | | If a control with a given name already exists, it would *not* be replaced with a new one. If you want to replace an existing control, use the [setControl](formgroup#setControl) method instead. This method also updates the value and validity of the control. | | removeControl() | | --- | | Remove a control from this group. In a strongly-typed group, required controls cannot be removed. | | `removeControl(name: string, options?: { emitEvent?: boolean; }): void` Parameters | | | | | --- | --- | --- | | `name` | `string` | | | `options` | `object` | Optional. Default is `undefined`. | Returns `void` | | `removeControl<S extends string>(name: ɵOptionalKeys<TControl> & S, options?: { emitEvent?: boolean; }): void` Parameters | | | | | --- | --- | --- | | `name` | `ɵOptionalKeys<TControl> & S` | | | `options` | `object` | Optional. Default is `undefined`. | Returns `void` | | This method also updates the value and validity of the control. | | setControl() | | --- | | Replace an existing control. In a strongly-typed group, the control must be in the group's type (possibly as an optional key). `setControl<K extends string & keyof TControl>(name: K, control: TControl[K], options?: { emitEvent?: boolean; }): void` Parameters | | | | | --- | --- | --- | | `name` | `K` | The control name to replace in the collection | | `control` | `TControl[K]` | Provides the control for the given name | | `options` | `object` | Specifies whether this FormGroup instance should emit events after an existing control is replaced.* `emitEvent`: When true or not supplied (the default), both the `statusChanges` and `valueChanges` observables emit events with the latest status and value when the control is replaced with a new one. When false, no events are emitted. Optional. Default is `undefined`. | Returns `void` | | `setControl(name: string, control: AbstractControl<any, any>, options?: { emitEvent?: boolean; }): void` Parameters | | | | | --- | --- | --- | | `name` | `string` | | | `control` | `[AbstractControl](abstractcontrol)<any, any>` | | | `options` | `object` | Optional. Default is `undefined`. | Returns `void` | | If a control with a given name does not exist in this `[FormGroup](formgroup)`, it will be added. | | contains() | | --- | | Check whether there is an enabled control with the given name in the group. `contains<K extends string>(controlName: K): boolean` Parameters | | | | | --- | --- | --- | | `controlName` | `K` | The control name to check for existence in the collection | Returns `boolean`: false for disabled controls, true otherwise. | | `contains(controlName: string): boolean` Parameters | | | | | --- | --- | --- | | `controlName` | `string` | | Returns `boolean` | | Reports false for disabled controls. If you'd like to check for existence in the group only, use [get](abstractcontrol#get) instead. | | setValue() | | --- | | Sets the value of the `[FormGroup](formgroup)`. It accepts an object that matches the structure of the group, with control names as keys. | | `setValue(value: ɵIsAny<TControl, { [key: string]: any; }, { [K in keyof TControl]: ɵRawValue<TControl[K]>; }>, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void` Parameters | | | | | --- | --- | --- | | `value` | `ɵIsAny<TControl, { [key: string]: any; }, { [K in keyof TControl]: ɵRawValue<TControl[K]>; }>` | The new value for the control that matches the structure of the group. | | `options` | `object` | Configuration options that determine how the control propagates changes and emits events after the value changes. The configuration options are passed to the [updateValueAndValidity](abstractcontrol#updateValueAndValidity) method.* `onlySelf`: When true, each change only affects this control, and not its parent. Default is false. * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and `valueChanges` observables emit events with the latest status and value when the control value is updated. When false, no events are emitted. Optional. Default is `{}`. | Returns `void` Throws `Error` When strict checks fail, such as setting the value of a control that doesn't exist or if you exclude a value of a control that does exist. | | Usage Notes Set the complete value for the form group ``` const form = new FormGroup({ first: new FormControl(), last: new FormControl() }); console.log(form.value); // {first: null, last: null} form.setValue({first: 'Nancy', last: 'Drew'}); console.log(form.value); // {first: 'Nancy', last: 'Drew'} ``` | | patchValue() | | --- | | Patches the value of the `[FormGroup](formgroup)`. It accepts an object with control names as keys, and does its best to match the values to the correct controls in the group. | | `patchValue(value: ɵIsAny<TControl, { [key: string]: any; }, Partial<{ [K in keyof TControl]: ɵValue<TControl[K]>; }>>, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void` Parameters | | | | | --- | --- | --- | | `value` | `ɵIsAny<TControl, { [key: string]: any; }, Partial<{ [K in keyof TControl]: ɵValue<TControl[K]>; }>>` | The object that matches the structure of the group. | | `options` | `object` | Configuration options that determine how the control propagates changes and emits events after the value is patched.* `onlySelf`: When true, each change only affects this control and not its parent. Default is true. * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and `valueChanges` observables emit events with the latest status and value when the control value is updated. When false, no events are emitted. The configuration options are passed to the [updateValueAndValidity](abstractcontrol#updateValueAndValidity) method. Optional. Default is `{}`. | Returns `void` | | It accepts both super-sets and sub-sets of the group without throwing an error. | | Usage Notes Patch the value for a form group ``` const form = new FormGroup({ first: new FormControl(), last: new FormControl() }); console.log(form.value); // {first: null, last: null} form.patchValue({first: 'Nancy'}); console.log(form.value); // {first: 'Nancy', last: null} ``` | | reset() | | --- | | Resets the `[FormGroup](formgroup)`, marks all descendants `pristine` and `untouched` and sets the value of all descendants to their default values, or null if no defaults were provided. | | `reset(value: ɵIsAny<TControl, any, ɵIsAny<TControl, { [key: string]: any; }, Partial<{ [K in keyof TControl]: ɵValue<TControl[K]>; }>>> = {} as unknown as ɵFormGroupValue<TControl>, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void` Parameters | | | | | --- | --- | --- | | `value` | `ɵIsAny<TControl, any, ɵIsAny<TControl, { [key: string]: any; }, Partial<{ [K in keyof TControl]: ɵValue<TControl[K]>; }>>>` | Resets the control with an initial value, or an object that defines the initial value and disabled state. Optional. Default is `{} as unknown as ɵFormGroupValue<TControl>`. | | `options` | `object` | Configuration options that determine how the control propagates changes and emits events when the group is reset.* `onlySelf`: When true, each change only affects this control, and not its parent. Default is false. * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and `valueChanges` observables emit events with the latest status and value when the control is reset. When false, no events are emitted. The configuration options are passed to the [updateValueAndValidity](abstractcontrol#updateValueAndValidity) method. Optional. Default is `{}`. | Returns `void` | | You reset to a specific form state by passing in a map of states that matches the structure of your form, with control names as keys. The state is a standalone value or a form state object with both a value and a disabled status. | | Usage Notes Reset the form group values ``` const form = new FormGroup({ first: new FormControl('first name'), last: new FormControl('last name') }); console.log(form.value); // {first: 'first name', last: 'last name'} form.reset({ first: 'name', last: 'last name' }); console.log(form.value); // {first: 'name', last: 'last name'} ``` Reset the form group values and disabled status ``` const form = new FormGroup({ first: new FormControl('first name'), last: new FormControl('last name') }); form.reset({ first: {value: 'name', disabled: true}, last: 'last' }); console.log(form.value); // {last: 'last'} console.log(form.get('first').status); // 'DISABLED' ``` | | getRawValue() | | --- | | The aggregate value of the `[FormGroup](formgroup)`, including any disabled controls. | | `getRawValue(): ɵTypedOrUntyped<TControl, ɵFormGroupRawValue<TControl>, any>` Parameters There are no parameters. Returns `ɵTypedOrUntyped<TControl, ɵFormGroupRawValue<TControl>, any>` | | Retrieves all values regardless of disabled status. | Usage notes ----------- ### Create a form group with 2 controls ``` const form = new FormGroup({ first: new FormControl('Nancy', Validators.minLength(2)), last: new FormControl('Drew'), }); console.log(form.value); // {first: 'Nancy', last; 'Drew'} console.log(form.status); // 'VALID' ``` ### The type argument, and optional controls `[FormGroup](formgroup)` accepts one generic argument, which is an object containing its inner controls. This type will usually be inferred automatically, but you can always specify it explicitly if you wish. If you have controls that are optional (i.e. they can be removed, you can use the `?` in the type): ``` const form = new FormGroup<{ first: FormControl<string|null>, middle?: FormControl<string|null>, // Middle name is optional. last: FormControl<string|null>, }>({ first: new FormControl('Nancy'), last: new FormControl('Drew'), }); ``` ### Create a form group with a group-level validator You include group-level validators as the second arg, or group-level async validators as the third arg. These come in handy when you want to perform validation that considers the value of more than one child control. ``` const form = new FormGroup({ password: new FormControl('', Validators.minLength(2)), passwordConfirm: new FormControl('', Validators.minLength(2)), }, passwordMatchValidator); function passwordMatchValidator(g: FormGroup) { return g.get('password').value === g.get('passwordConfirm').value ? null : {'mismatch': true}; } ``` Like `[FormControl](formcontrol)` instances, you choose to pass in validators and async validators as part of an options object. ``` const form = new FormGroup({ password: new FormControl('') passwordConfirm: new FormControl('') }, { validators: passwordMatchValidator, asyncValidators: otherValidator }); ``` ### Set the updateOn property for all controls in a form group The options object is used to set a default value for each child control's `updateOn` property. If you set `updateOn` to `'blur'` at the group level, all child controls default to 'blur', unless the child has explicitly specified a different `updateOn` value. ``` const c = new FormGroup({ one: new FormControl() }, { updateOn: 'blur' }); ``` ### Using a FormGroup with optional controls It is possible to have optional controls in a FormGroup. An optional control can be removed later using `removeControl`, and can be omitted when calling `reset`. Optional controls must be declared optional in the group's type. ``` const c = new FormGroup<{one?: FormControl<string>}>({ one: new FormControl('') }); ``` Notice that `c.value.one` has type `string|null|undefined`. This is because calling `c.reset({})` without providing the optional key `one` will cause it to become `null`.
programming_docs
angular AbstractControlDirective AbstractControlDirective ======================== `class` Base class for control directives. [See more...](abstractcontroldirective#description) ``` abstract class AbstractControlDirective { abstract control: AbstractControl | null value: any valid: boolean | null invalid: boolean | null pending: boolean | null disabled: boolean | null enabled: boolean | null errors: ValidationErrors | null pristine: boolean | null dirty: boolean | null touched: boolean | null status: string | null untouched: boolean | null statusChanges: Observable<any> | null valueChanges: Observable<any> | null path: string[] | null validator: ValidatorFn | null asyncValidator: AsyncValidatorFn | null reset(value: any = undefined): void hasError(errorCode: string, path?: string | (string | number)[]): boolean getError(errorCode: string, path?: string | (string | number)[]): any } ``` Subclasses ---------- * `[ControlContainer](controlcontainer)` + `[AbstractFormGroupDirective](abstractformgroupdirective)` - `[NgModelGroup](ngmodelgroup)` - `[FormGroupName](formgroupname)` + `[NgForm](ngform)` + `[FormGroupDirective](formgroupdirective)` + `[FormArrayName](formarrayname)` * `[NgControl](ngcontrol)` + `[NgModel](ngmodel)` + `[FormControlDirective](formcontroldirective)` + `[FormControlName](formcontrolname)` Description ----------- This class is only used internally in the `[ReactiveFormsModule](reactiveformsmodule)` and the `[FormsModule](formsmodule)`. Properties ---------- | Property | Description | | --- | --- | | `abstract control: [AbstractControl](abstractcontrol) | null` | Read-Only A reference to the underlying control. | | `value: any` | Read-Only Reports the value of the control if it is present, otherwise null. | | `valid: boolean | null` | Read-Only Reports whether the control is valid. A control is considered valid if no validation errors exist with the current value. If the control is not present, null is returned. | | `invalid: boolean | null` | Read-Only Reports whether the control is invalid, meaning that an error exists in the input value. If the control is not present, null is returned. | | `pending: boolean | null` | Read-Only Reports whether a control is pending, meaning that that async validation is occurring and errors are not yet available for the input value. If the control is not present, null is returned. | | `disabled: boolean | null` | Read-Only Reports whether the control is disabled, meaning that the control is disabled in the UI and is exempt from validation checks and excluded from aggregate values of ancestor controls. If the control is not present, null is returned. | | `enabled: boolean | null` | Read-Only Reports whether the control is enabled, meaning that the control is included in ancestor calculations of validity or value. If the control is not present, null is returned. | | `errors: [ValidationErrors](validationerrors) | null` | Read-Only Reports the control's validation errors. If the control is not present, null is returned. | | `pristine: boolean | null` | Read-Only Reports whether the control is pristine, meaning that the user has not yet changed the value in the UI. If the control is not present, null is returned. | | `dirty: boolean | null` | Read-Only Reports whether the control is dirty, meaning that the user has changed the value in the UI. If the control is not present, null is returned. | | `touched: boolean | null` | Read-Only Reports whether the control is touched, meaning that the user has triggered a `blur` event on it. If the control is not present, null is returned. | | `status: string | null` | Read-Only Reports the validation status of the control. Possible values include: 'VALID', 'INVALID', 'DISABLED', and 'PENDING'. If the control is not present, null is returned. | | `untouched: boolean | null` | Read-Only Reports whether the control is untouched, meaning that the user has not yet triggered a `blur` event on it. If the control is not present, null is returned. | | `statusChanges: Observable<any> | null` | Read-Only Returns a multicasting observable that emits a validation status whenever it is calculated for the control. If the control is not present, null is returned. | | `valueChanges: Observable<any> | null` | Read-Only Returns a multicasting observable of value changes for the control that emits every time the value of the control changes in the UI or programmatically. If the control is not present, null is returned. | | `path: string[] | null` | Read-Only Returns an array that represents the path from the top-level form to this control. Each index is the string name of the control on that level. | | `validator: [ValidatorFn](validatorfn) | null` | Read-Only Synchronous validator function composed of all the synchronous validators registered with this directive. | | `asyncValidator: [AsyncValidatorFn](asyncvalidatorfn) | null` | Read-Only Asynchronous validator function composed of all the asynchronous validators registered with this directive. | Methods ------- | reset() | | --- | | Resets the control with the provided value if the control is present. | | `reset(value: any = undefined): void` Parameters | | | | | --- | --- | --- | | `value` | `any` | Optional. Default is `undefined`. | Returns `void` | | hasError() | | --- | | Reports whether the control with the given path has the error specified. | | `hasError(errorCode: string, path?: string | (string | number)[]): boolean` Parameters | | | | | --- | --- | --- | | `errorCode` | `string` | The code of the error to check | | `path` | `string | (string | number)[]` | A list of control names that designates how to move from the current control to the control that should be queried for errors. Optional. Default is `undefined`. | Returns `boolean`: whether the given error is present in the control at the given path. If the control is not present, false is returned. | | Usage Notes For example, for the following `[FormGroup](formgroup)`: ``` form = new FormGroup({ address: new FormGroup({ street: new FormControl() }) }); ``` The path to the 'street' control from the root form would be 'address' -> 'street'. It can be provided to this method in one of two formats:1. An array of string control names, e.g. `['address', 'street']` 2. A period-delimited list of control names in one string, e.g. `'address.street'` If no path is given, this method checks for the error on the current control. | | getError() | | --- | | Reports error data for the control with the given path. | | `getError(errorCode: string, path?: string | (string | number)[]): any` Parameters | | | | | --- | --- | --- | | `errorCode` | `string` | The code of the error to check | | `path` | `string | (string | number)[]` | A list of control names that designates how to move from the current control to the control that should be queried for errors. Optional. Default is `undefined`. | Returns `any`: error data for that particular error. If the control or error is not present, null is returned. | | Usage Notes For example, for the following `[FormGroup](formgroup)`: ``` form = new FormGroup({ address: new FormGroup({ street: new FormControl() }) }); ``` The path to the 'street' control from the root form would be 'address' -> 'street'. It can be provided to this method in one of two formats:1. An array of string control names, e.g. `['address', 'street']` 2. A period-delimited list of control names in one string, e.g. `'address.street'` | angular CheckboxRequiredValidator CheckboxRequiredValidator ========================= `directive` A Directive that adds the `required` validator to checkbox controls marked with the `required` attribute. The directive is provided with the `[NG\_VALIDATORS](ng_validators)` multi-provider list. See also -------- * [Form Validation](../../guide/form-validation) Exported from ------------- * [``` FormsModule ```](formsmodule) * [``` ReactiveFormsModule ```](reactiveformsmodule) Selectors --------- * `input[type=checkbox][required][[formControlName](formcontrolname)]` * `input[type=checkbox][required][formControl]` * `input[type=checkbox][required][[ngModel](ngmodel)]` ### Inherited from `[RequiredValidator](requiredvalidator)` * `[@Input()required: boolean | string](requiredvalidator#required)` Description ----------- ### Adding a required checkbox validator using template-driven forms The following example shows how to add a checkbox required validator to an input attached to an ngModel binding. ``` <input type="checkbox" name="active" ngModel required> ``` angular isFormControl isFormControl ============= `const` Asserts that the given control is an instance of `[FormControl](formcontrol)` ### `const isFormControl: (control: unknown) => control is FormControl<any>;` angular UntypedFormBuilder UntypedFormBuilder ================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` UntypedFormBuilder is the same as @see FormBuilder, but it provides untyped controls. ``` class UntypedFormBuilder extends FormBuilder { group(controlsConfig: { [key: string]: any; }, options: AbstractControlOptions | { [key: string]: any; } = null): UntypedFormGroup control(formState: any, validatorOrOpts?: ValidatorFn | FormControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]): UntypedFormControl array(controlsConfig: any[], validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]): UntypedFormArray // inherited from forms/FormBuilder nonNullable: NonNullableFormBuilder group(controls: { [key: string]: any; }, options: AbstractControlOptions | { [key: string]: any; } = null): FormGroup record<T>(controls: { [key: string]: T; }, options: AbstractControlOptions = null): FormRecord<ɵElement<T, null>> control<T>(formState: T | FormControlState<T>, validatorOrOpts?: ValidatorFn | FormControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]): FormControl array<T>(controls: T[], validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]): FormArray<ɵElement<T, null>> } ``` Provided in ----------- * ``` 'root' ``` Methods ------- | group() | | --- | | Like `[FormBuilder](formbuilder)#group`, except the resulting group is untyped. `group(controlsConfig: { [key: string]: any; }, options?: AbstractControlOptions): UntypedFormGroup` Parameters | | | | | --- | --- | --- | | `controlsConfig` | `object` | | | `options` | `[AbstractControlOptions](abstractcontroloptions)` | Optional. Default is `undefined`. | Returns `[UntypedFormGroup](untypedformgroup)` | | `group(controlsConfig: { [key: string]: any; }, options: { [key: string]: any; }): UntypedFormGroup` **Deprecated** This API is not typesafe and can result in issues with Closure Compiler renaming. Use the `[FormBuilder](formbuilder)#group` overload with `[AbstractControlOptions](abstractcontroloptions)` instead. Parameters | | | | | --- | --- | --- | | `controlsConfig` | `object` | | | `options` | `object` | | Returns `[UntypedFormGroup](untypedformgroup)` | | control() | | --- | | Like `[FormBuilder](formbuilder)#control`, except the resulting control is untyped. | | `control(formState: any, validatorOrOpts?: ValidatorFn | FormControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]): UntypedFormControl` Parameters | | | | | --- | --- | --- | | `formState` | `any` | | | `validatorOrOpts` | `[ValidatorFn](validatorfn) | [FormControlOptions](formcontroloptions) | [ValidatorFn](validatorfn)[]` | Optional. Default is `undefined`. | | `asyncValidator` | `[AsyncValidatorFn](asyncvalidatorfn) | [AsyncValidatorFn](asyncvalidatorfn)[]` | Optional. Default is `undefined`. | Returns `[UntypedFormControl](untypedformcontrol)` | | array() | | --- | | Like `[FormBuilder](formbuilder)#array`, except the resulting array is untyped. | | `array(controlsConfig: any[], validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]): UntypedFormArray` Parameters | | | | | --- | --- | --- | | `controlsConfig` | `any[]` | | | `validatorOrOpts` | `[ValidatorFn](validatorfn) | [AbstractControlOptions](abstractcontroloptions) | [ValidatorFn](validatorfn)[]` | Optional. Default is `undefined`. | | `asyncValidator` | `[AsyncValidatorFn](asyncvalidatorfn) | [AsyncValidatorFn](asyncvalidatorfn)[]` | Optional. Default is `undefined`. | Returns `[UntypedFormArray](untypedformarray)` | angular FormControlState FormControlState ================ `interface` FormControlState is a boxed form value. It is an object with a `value` key and a `disabled` key. ``` interface FormControlState<T> { value: T disabled: boolean } ``` Properties ---------- | Property | Description | | --- | --- | | `value: T` | | | `disabled: boolean` | | angular SetDisabledStateOption SetDisabledStateOption ====================== `type-alias` The type for CALL\_SET\_DISABLED\_STATE. If `always`, then ControlValueAccessor will always call `setDisabledState` when attached, which is the most correct behavior. Otherwise, it will only be called when disabled, which is the legacy behavior for compatibility. ``` type SetDisabledStateOption = 'whenDisabledForLegacyCode' | 'always'; ``` See also -------- * `FormsModule.withConfig` angular NG_VALIDATORS NG\_VALIDATORS ============== `const` An `[InjectionToken](../core/injectiontoken)` for registering additional synchronous validators used with `[AbstractControl](abstractcontrol)`s. ### `const NG_VALIDATORS: InjectionToken<(Function | Validator)[]>;` #### See also * `[NG\_ASYNC\_VALIDATORS](ng_async_validators)` Usage notes ----------- #### Providing a custom validator The following example registers a custom validator directive. Adding the validator to the existing collection of validators requires the `multi: true` option. ``` @Directive({ selector: '[customValidator]', providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}] }) class CustomValidatorDirective implements Validator { validate(control: AbstractControl): ValidationErrors | null { return { 'custom': true }; } } ``` angular UntypedFormControl UntypedFormControl ================== `type-alias` UntypedFormControl is a non-strongly-typed version of @see FormControl. ``` type UntypedFormControl = FormControl<any>; ``` angular NgControlStatusGroup NgControlStatusGroup ==================== `directive` Directive automatically applied to Angular form groups that sets CSS classes based on control status (valid/invalid/dirty/etc). On groups, this includes the additional class ng-submitted. See also -------- * `[NgControlStatus](ngcontrolstatus)` Exported from ------------- * [``` ReactiveFormsModule ```](reactiveformsmodule) * [``` FormsModule ```](formsmodule) Selectors --------- * `[[formGroupName](formgroupname)]` * `[[formArrayName](formarrayname)]` * `[[ngModelGroup](ngmodelgroup)]` * `[formGroup]` * `form*:not([ngNoForm])*` * `[[ngForm](ngform)]` angular isFormRecord isFormRecord ============ `const` Asserts that the given control is an instance of `[FormRecord](formrecord)` ### `const isFormRecord: (control: unknown) => control is FormRecord<AbstractControl<any, any>>;` angular NumberValueAccessor NumberValueAccessor =================== `directive` The `[ControlValueAccessor](controlvalueaccessor)` for writing a number value and listening to number input changes. The value accessor is used by the `[FormControlDirective](formcontroldirective)`, `[FormControlName](formcontrolname)`, and `[NgModel](ngmodel)` directives. Exported from ------------- * [``` ReactiveFormsModule ```](reactiveformsmodule) * [``` FormsModule ```](formsmodule) Selectors --------- * `input[type=number][[formControlName](formcontrolname)]` * `input[type=number][formControl]` * `input[type=number][[ngModel](ngmodel)]` Description ----------- ### Using a number input with a reactive form. The following example shows how to use a number input with a reactive form. ``` const totalCountControl = new FormControl(); ``` ``` <input type="number" [formControl]="totalCountControl"> ``` angular FormGroupDirective FormGroupDirective ================== `directive` Binds an existing `[FormGroup](formgroup)` or `[FormRecord](formrecord)` to a DOM element. [See more...](formgroupdirective#description) See also -------- * [Reactive Forms Guide](../../guide/reactive-forms) * `[AbstractControl](abstractcontrol)` Exported from ------------- * [``` ReactiveFormsModule ```](reactiveformsmodule) Selectors --------- * `[formGroup]` Properties ---------- | Property | Description | | --- | --- | | `submitted: boolean` | Read-Only Reports whether the form submission has been triggered. | | `directives: [FormControlName](formcontrolname)[]` | Tracks the list of added `[FormControlName](formcontrolname)` instances | | `@[Input](../core/input)('formGroup')form: [FormGroup](formgroup)` | Tracks the `[FormGroup](formgroup)` bound to this directive. | | `@[Output](../core/output)()ngSubmit: [EventEmitter](../core/eventemitter)` | Emits an event when the form submission has been triggered. | | `formDirective: [Form](form)` | Read-Only Returns this directive's instance. | | `control: [FormGroup](formgroup)` | Read-Only Returns the `[FormGroup](formgroup)` bound to this directive. | | `path: string[]` | Read-Only Returns an array representing the path to this group. Because this directive always lives at the top level of a form, it always an empty array. | ### Inherited from `[ControlContainer](controlcontainer)` * `[name: string | number | null](controlcontainer#name)` * `[formDirective: Form | null](controlcontainer#formDirective)` * `[path: string[] | null](controlcontainer#path)` ### Inherited from `[AbstractControlDirective](abstractcontroldirective)` * `[abstract control: AbstractControl | null](abstractcontroldirective#control)` * `[value: any](abstractcontroldirective#value)` * `[valid: boolean | null](abstractcontroldirective#valid)` * `[invalid: boolean | null](abstractcontroldirective#invalid)` * `[pending: boolean | null](abstractcontroldirective#pending)` * `[disabled: boolean | null](abstractcontroldirective#disabled)` * `[enabled: boolean | null](abstractcontroldirective#enabled)` * `[errors: ValidationErrors | null](abstractcontroldirective#errors)` * `[pristine: boolean | null](abstractcontroldirective#pristine)` * `[dirty: boolean | null](abstractcontroldirective#dirty)` * `[touched: boolean | null](abstractcontroldirective#touched)` * `[status: string | null](abstractcontroldirective#status)` * `[untouched: boolean | null](abstractcontroldirective#untouched)` * `[statusChanges: Observable<any> | null](abstractcontroldirective#statusChanges)` * `[valueChanges: Observable<any> | null](abstractcontroldirective#valueChanges)` * `[path: string[] | null](abstractcontroldirective#path)` * `[validator: ValidatorFn | null](abstractcontroldirective#validator)` * `[asyncValidator: AsyncValidatorFn | null](abstractcontroldirective#asyncValidator)` Template variable references ---------------------------- | Identifier | Usage | | --- | --- | | `[ngForm](ngform)` | `#myTemplateVar="[ngForm](ngform)"` | Description ----------- This directive accepts an existing `[FormGroup](formgroup)` instance. It will then use this `[FormGroup](formgroup)` instance to match any child `[FormControl](formcontrol)`, `[FormGroup](formgroup)`/`[FormRecord](formrecord)`, and `[FormArray](formarray)` instances to child `[FormControlName](formcontrolname)`, `[FormGroupName](formgroupname)`, and `[FormArrayName](formarrayname)` directives. ### Register Form Group The following example registers a `[FormGroup](formgroup)` with first name and last name controls, and listens for the *ngSubmit* event when the button is clicked. ``` import {Component} from '@angular/core'; import {FormControl, FormGroup, Validators} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form [formGroup]="form" (ngSubmit)="onSubmit()"> <div *ngIf="first.invalid"> Name is too short. </div> <input formControlName="first" placeholder="First name"> <input formControlName="last" placeholder="Last name"> <button type="submit">Submit</button> </form> <button (click)="setValue()">Set preset value</button> `, }) export class SimpleFormGroup { form = new FormGroup({ first: new FormControl('Nancy', Validators.minLength(2)), last: new FormControl('Drew'), }); get first(): any { return this.form.get('first'); } onSubmit(): void { console.log(this.form.value); // {first: 'Nancy', last: 'Drew'} } setValue() { this.form.setValue({first: 'Carson', last: 'Drew'}); } } ``` Methods ------- | addControl() | | --- | | Method that sets up the control directive in this group, re-calculates its value and validity, and adds the instance to the internal list of directives. | | `addControl(dir: FormControlName): FormControl` Parameters | | | | | --- | --- | --- | | `dir` | `[FormControlName](formcontrolname)` | The `[FormControlName](formcontrolname)` directive instance. | Returns `[FormControl](formcontrol)` | | getControl() | | --- | | Retrieves the `[FormControl](formcontrol)` instance from the provided `[FormControlName](formcontrolname)` directive | | `getControl(dir: FormControlName): FormControl` Parameters | | | | | --- | --- | --- | | `dir` | `[FormControlName](formcontrolname)` | The `[FormControlName](formcontrolname)` directive instance. | Returns `[FormControl](formcontrol)` | | removeControl() | | --- | | Removes the `[FormControlName](formcontrolname)` instance from the internal list of directives | | `removeControl(dir: FormControlName): void` Parameters | | | | | --- | --- | --- | | `dir` | `[FormControlName](formcontrolname)` | The `[FormControlName](formcontrolname)` directive instance. | Returns `void` | | addFormGroup() | | --- | | Adds a new `[FormGroupName](formgroupname)` directive instance to the form. | | `addFormGroup(dir: FormGroupName): void` Parameters | | | | | --- | --- | --- | | `dir` | `[FormGroupName](formgroupname)` | The `[FormGroupName](formgroupname)` directive instance. | Returns `void` | | removeFormGroup() | | --- | | Performs the necessary cleanup when a `[FormGroupName](formgroupname)` directive instance is removed from the view. | | `removeFormGroup(dir: FormGroupName): void` Parameters | | | | | --- | --- | --- | | `dir` | `[FormGroupName](formgroupname)` | The `[FormGroupName](formgroupname)` directive instance. | Returns `void` | | getFormGroup() | | --- | | Retrieves the `[FormGroup](formgroup)` for a provided `[FormGroupName](formgroupname)` directive instance | | `getFormGroup(dir: FormGroupName): FormGroup` Parameters | | | | | --- | --- | --- | | `dir` | `[FormGroupName](formgroupname)` | The `[FormGroupName](formgroupname)` directive instance. | Returns `[FormGroup](formgroup)` | | addFormArray() | | --- | | Performs the necessary setup when a `[FormArrayName](formarrayname)` directive instance is added to the view. | | `addFormArray(dir: FormArrayName): void` Parameters | | | | | --- | --- | --- | | `dir` | `[FormArrayName](formarrayname)` | The `[FormArrayName](formarrayname)` directive instance. | Returns `void` | | removeFormArray() | | --- | | Performs the necessary cleanup when a `[FormArrayName](formarrayname)` directive instance is removed from the view. | | `removeFormArray(dir: FormArrayName): void` Parameters | | | | | --- | --- | --- | | `dir` | `[FormArrayName](formarrayname)` | The `[FormArrayName](formarrayname)` directive instance. | Returns `void` | | getFormArray() | | --- | | Retrieves the `[FormArray](formarray)` for a provided `[FormArrayName](formarrayname)` directive instance. | | `getFormArray(dir: FormArrayName): FormArray` Parameters | | | | | --- | --- | --- | | `dir` | `[FormArrayName](formarrayname)` | The `[FormArrayName](formarrayname)` directive instance. | Returns `[FormArray](formarray)` | | updateModel() | | --- | | Sets the new value for the provided `[FormControlName](formcontrolname)` directive. | | `updateModel(dir: FormControlName, value: any): void` Parameters | | | | | --- | --- | --- | | `dir` | `[FormControlName](formcontrolname)` | The `[FormControlName](formcontrolname)` directive instance. | | `value` | `any` | The new value for the directive's control. | Returns `void` | | onSubmit() | | --- | | Method called with the "submit" event is triggered on the form. Triggers the `ngSubmit` emitter to emit the "submit" event as its payload. | | `onSubmit($event: Event): boolean` Parameters | | | | | --- | --- | --- | | `$event` | `[Event](../router/event)` | The "submit" event object | Returns `boolean` | | onReset() | | --- | | Method called when the "reset" event is triggered on the form. | | `onReset(): void` Parameters There are no parameters. Returns `void` | | resetForm() | | --- | | Resets the form to an initial value and resets its submitted status. | | `resetForm(value: any = undefined): void` Parameters | | | | | --- | --- | --- | | `value` | `any` | The new value for the form. Optional. Default is `undefined`. | Returns `void` | ### Inherited from `[AbstractControlDirective](abstractcontroldirective)` * `[reset(value: any = undefined): void](abstractcontroldirective#reset)` * `[hasError(errorCode: string, path?: string | (string | number)[]): boolean](abstractcontroldirective#hasError)` * `[getError(errorCode: string, path?: string | (string | number)[]): any](abstractcontroldirective#getError)`
programming_docs
angular COMPOSITION_BUFFER_MODE COMPOSITION\_BUFFER\_MODE ========================= `const` Provide this token to control if form directives buffer IME input until the "compositionend" event occurs. ### `const COMPOSITION_BUFFER_MODE: InjectionToken<boolean>;` angular NG_ASYNC_VALIDATORS NG\_ASYNC\_VALIDATORS ===================== `const` An `[InjectionToken](../core/injectiontoken)` for registering additional asynchronous validators used with `[AbstractControl](abstractcontrol)`s. ### `const NG_ASYNC_VALIDATORS: InjectionToken<(Function | Validator)[]>;` #### See also * `[NG\_VALIDATORS](ng_validators)` Usage notes ----------- #### Provide a custom async validator directive The following example implements the `[AsyncValidator](asyncvalidator)` interface to create an async validator directive with a custom error key. ``` @Directive({ selector: '[customAsyncValidator]', providers: [{provide: NG_ASYNC_VALIDATORS, useExisting: CustomAsyncValidatorDirective, multi: true}] }) class CustomAsyncValidatorDirective implements AsyncValidator { validate(control: AbstractControl): Promise<ValidationErrors|null> { return Promise.resolve({'custom': true}); } } ``` angular UntypedFormGroup UntypedFormGroup ================ `type-alias` UntypedFormGroup is a non-strongly-typed version of @see FormGroup. ``` type UntypedFormGroup = FormGroup<any>; ``` angular FormControlStatus FormControlStatus ================= `type-alias` A form can have several different statuses. Each possible status is returned as a string literal. [See more...](formcontrolstatus#description) ``` type FormControlStatus = 'VALID' | 'INVALID' | 'PENDING' | 'DISABLED'; ``` Description ----------- * **VALID**: Reports that a control is valid, meaning that no errors exist in the input value. * **INVALID**: Reports that a control is invalid, meaning that an error exists in the input value. * **PENDING**: Reports that a control is pending, meaning that that async validation is occurring and errors are not yet available for the input value. * **DISABLED**: Reports that a control is disabled, meaning that the control is exempt from ancestor calculations of validity or value. angular DoCheck DoCheck ======= `interface` A lifecycle hook that invokes a custom change-detection function for a directive, in addition to the check performed by the default change-detector. [See more...](docheck#description) ``` interface DoCheck { ngDoCheck(): void } ``` Class implementations --------------------- * `[NgClass](../common/ngclass)` * `[NgFor](../common/ngfor)` * `[NgForOf](../common/ngforof)` * `[NgStyle](../common/ngstyle)` * `[NgSwitchCase](../common/ngswitchcase)` * `[UpgradeComponent](../upgrade/static/upgradecomponent)` See also -------- * `[OnChanges](onchanges)` * [Lifecycle hooks guide](../../guide/lifecycle-hooks) Description ----------- The default change-detection algorithm looks for differences by comparing bound-property values by reference across change detection runs. You can use this hook to check for and respond to changes by some other means. When the default change detector detects changes, it invokes `ngOnChanges()` if supplied, regardless of whether you perform additional change detection. Typically, you should not use both `[DoCheck](docheck)` and `[OnChanges](onchanges)` to respond to changes on the same input. Further information is available in the [Usage Notes...](docheck#usage-notes) Methods ------- | ngDoCheck() | | --- | | A callback method that performs change-detection, invoked after the default change-detector runs. See `[KeyValueDiffers](keyvaluediffers)` and `[IterableDiffers](iterablediffers)` for implementing custom change checking for collections. | | `ngDoCheck(): void` Parameters There are no parameters. Returns `void` | Usage notes ----------- The following snippet shows how a component can implement this interface to invoke it own change-detection cycle. ``` @Component({selector: 'my-cmp', template: `...`}) class MyComponent implements DoCheck { ngDoCheck() { // ... } } ``` For a more complete example and discussion, see [Defining custom change detection](../../guide/lifecycle-hooks#defining-custom-change-detection). angular AbstractType AbstractType ============ `interface` Represents an abstract class `T`, if applied to a concrete class it would stop being instantiable. ``` interface AbstractType<T> extends Function { prototype: T } ``` Properties ---------- | Property | Description | | --- | --- | | `prototype: T` | | angular COMPILER_OPTIONS COMPILER\_OPTIONS ================= `const` Token to provide CompilerOptions in the platform injector. ### `const COMPILER_OPTIONS: InjectionToken<CompilerOptions[]>;` angular forwardRef forwardRef ========== `function` Allows to refer to references which are not yet defined. [See more...](forwardref#description) ### `forwardRef(forwardRefFn: ForwardRefFn): Type<any>` ###### Parameters | | | | | --- | --- | --- | | `forwardRefFn` | `[ForwardRefFn](forwardreffn)` | | ###### Returns `[Type](type)<any>` Description ----------- For instance, `[forwardRef](forwardref)` is used when the `token` which we need to refer to for the purposes of DI is declared, but not yet defined. It is also used when the `token` which we use when creating a query is not yet defined. Further information is available in the [Usage Notes...](forwardref#usage-notes) Usage notes ----------- ### Example ``` @Injectable() class Door { lock: Lock; // Door attempts to inject Lock, despite it not being defined yet. // forwardRef makes this possible. constructor(@Inject(forwardRef(() => Lock)) lock: Lock) { this.lock = lock; } } // Only at this point Lock is defined. class Lock {} const injector = Injector.create({providers: [{provide: Lock, deps: []}, {provide: Door, deps: [Lock]}]}); expect(injector.get(Door) instanceof Door).toBe(true); expect(injector.get(Door).lock instanceof Lock).toBe(true); ``` angular defineInjectable defineInjectable ================ `const` `deprecated` **Deprecated:** in v8, delete after v10. This API should be used only by generated code, and that code should now use ɵɵdefineInjectable instead. ### `const defineInjectable: <T>(opts: { token: unknown; providedIn?: "root" | Type<any> | "platform" | "any" | "environment"; factory: () => T; }) => unknown;` angular APP_INITIALIZER APP\_INITIALIZER ================ `const` A [DI token](../../guide/glossary#di-token "DI token definition") that you can use to provide one or more initialization functions. [See more...](app_initializer#description) ### `const APP_INITIALIZER: InjectionToken<readonly (() => void | Observable<unknown> | Promise<unknown>)[]>;` #### See also * `[ApplicationInitStatus](applicationinitstatus)` Description ----------- The provided functions are injected at application startup and executed during app initialization. If any of these functions returns a Promise or an Observable, initialization does not complete until the Promise is resolved or the Observable is completed. You can, for example, create a factory function that loads language data or an external configuration, and provide that function to the `[APP\_INITIALIZER](app_initializer)` token. The function is executed during the application bootstrap process, and the needed data is available on startup. Further information is available in the [Usage Notes...](app_initializer#usage-notes) Usage notes ----------- The following example illustrates how to configure a multi-provider using `[APP\_INITIALIZER](app_initializer)` token and a function returning a promise. ``` function initializeApp(): Promise<any> { return new Promise((resolve, reject) => { // Do some asynchronous stuff resolve(); }); } @NgModule({ imports: [BrowserModule], declarations: [AppComponent], bootstrap: [AppComponent], providers: [{ provide: APP_INITIALIZER, useFactory: () => initializeApp, multi: true }] }) export class AppModule {} ``` It's also possible to configure a multi-provider using `[APP\_INITIALIZER](app_initializer)` token and a function returning an observable, see an example below. Note: the `[HttpClient](../common/http/httpclient)` in this example is used for demo purposes to illustrate how the factory function can work with other providers available through DI. ``` function initializeAppFactory(httpClient: HttpClient): () => Observable<any> { return () => httpClient.get("https://someUrl.com/api/user") .pipe( tap(user => { ... }) ); } @NgModule({ imports: [BrowserModule, HttpClientModule], declarations: [AppComponent], bootstrap: [AppComponent], providers: [{ provide: APP_INITIALIZER, useFactory: initializeAppFactory, deps: [HttpClient], multi: true }] }) export class AppModule {} ``` angular KeyValueDiffers KeyValueDiffers =============== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A repository of different Map diffing strategies used by NgClass, NgStyle, and others. ``` class KeyValueDiffers { static create<S>(factories: KeyValueDifferFactory[], parent?: KeyValueDiffers): KeyValueDiffers static extend<S>(factories: KeyValueDifferFactory[]): StaticProvider constructor(factories: KeyValueDifferFactory[]) factories: KeyValueDifferFactory[] find(kv: any): KeyValueDifferFactory } ``` Provided in ----------- * ``` 'root' ``` Static methods -------------- | create() | | --- | | `static create<S>(factories: KeyValueDifferFactory[], parent?: KeyValueDiffers): KeyValueDiffers` Parameters | | | | | --- | --- | --- | | `factories` | `[KeyValueDifferFactory](keyvaluedifferfactory)[]` | | | `parent` | `[KeyValueDiffers](keyvaluediffers)` | Optional. Default is `undefined`. | Returns `[KeyValueDiffers](keyvaluediffers)` | | extend() | | --- | | Takes an array of [`KeyValueDifferFactory`](keyvaluedifferfactory) and returns a provider used to extend the inherited [`KeyValueDiffers`](keyvaluediffers) instance with the provided factories and return a new [`KeyValueDiffers`](keyvaluediffers) instance. | | `static extend<S>(factories: KeyValueDifferFactory[]): StaticProvider` Parameters | | | | | --- | --- | --- | | `factories` | `[KeyValueDifferFactory](keyvaluedifferfactory)[]` | | Returns `[StaticProvider](staticprovider)` | | Usage Notes Example The following example shows how to extend an existing list of factories, which will only be applied to the injector for this component and its children. This step is all that's required to make a new [`KeyValueDiffer`](keyvaluediffer) available. ``` @Component({ viewProviders: [ KeyValueDiffers.extend([new ImmutableMapDiffer()]) ] }) ``` | Constructor ----------- | | | | | | --- | --- | --- | --- | | `constructor(factories: KeyValueDifferFactory[])` Parameters | | | | | --- | --- | --- | | `factories` | `[KeyValueDifferFactory](keyvaluedifferfactory)[]` | | | Properties ---------- | Property | Description | | --- | --- | | `factories: [KeyValueDifferFactory](keyvaluedifferfactory)[]` | **Deprecated** v4.0.0 - Should be private. | Methods ------- | find() | | --- | | `find(kv: any): KeyValueDifferFactory` Parameters | | | | | --- | --- | --- | | `kv` | `any` | | Returns `[KeyValueDifferFactory](keyvaluedifferfactory)` | angular DEFAULT_CURRENCY_CODE DEFAULT\_CURRENCY\_CODE ======================= `const` Provide this token to set the default currency code your application uses for CurrencyPipe when there is no currency code passed into it. This is only used by CurrencyPipe and has no relation to locale currency. Defaults to USD if not configured. [See more...](default_currency_code#description) ### `const DEFAULT_CURRENCY_CODE: InjectionToken<string>;` #### Description See the [i18n guide](../../guide/i18n-common-locale-id) for more information. > **Deprecation notice:** > > The default currency code is currently always `USD` but this is deprecated from v9. > > **In v10 the default currency code will be taken from the current locale.** > > If you need the previous behavior then set it by creating a `[DEFAULT\_CURRENCY\_CODE](default_currency_code)` provider in your application `[NgModule](ngmodule)`: > > > ``` > {provide: DEFAULT_CURRENCY_CODE, useValue: 'USD'} > ``` > Further information is available in the [Usage Notes...](default_currency_code#usage-notes) Usage notes ----------- #### Example ``` import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; platformBrowserDynamic().bootstrapModule(AppModule, { providers: [{provide: DEFAULT_CURRENCY_CODE, useValue: 'EUR' }] }); ``` angular RendererType2 RendererType2 ============= `interface` Used by `[RendererFactory2](rendererfactory2)` to associate custom rendering data and styles with a rendering implementation. ``` interface RendererType2 { id: string encapsulation: ViewEncapsulation styles: (string | any[])[] data: {...} } ``` Properties ---------- | Property | Description | | --- | --- | | `id: string` | A unique identifying string for the new renderer, used when creating unique styles for encapsulation. | | `encapsulation: [ViewEncapsulation](viewencapsulation)` | The view encapsulation type, which determines how styles are applied to DOM elements. One of* `Emulated` (default): Emulate native scoping of styles. * `Native`: Use the native encapsulation mechanism of the renderer. * `ShadowDom`: Use modern [Shadow DOM](https://w3c.github.io/webcomponents/spec/shadow/) and create a ShadowRoot for component's host element. * `None`: Do not provide any template or style encapsulation. | | `styles: (string | any[])[]` | Defines CSS styles to be stored on a renderer instance. | | `data: { [kind: string]: any; }` | Defines arbitrary developer-defined data to be stored on a renderer instance. This is useful for renderers that delegate to other renderers. | angular isStandalone isStandalone ============ `function` Checks whether a given Component, Directive or Pipe is marked as standalone. This will return false if passed anything other than a Component, Directive, or Pipe class See this guide for additional information: [https://angular.io/guide/standalone-components](../../guide/standalone-components) ### `isStandalone(type: Type<unknown>): boolean` ###### Parameters | | | | | --- | --- | --- | | `type` | `[Type](type)<unknown>` | A reference to a Component, Directive or Pipe. | ###### Returns `boolean` angular getDebugNode getDebugNode ============ `function` ### `getDebugNode(nativeNode: any): DebugNode | null` ###### Parameters | | | | | --- | --- | --- | | `nativeNode` | `any` | | ###### Returns `[DebugNode](debugnode) | null` angular KeyValueDiffer KeyValueDiffer ============== `interface` A differ that tracks changes made to an object over time. ``` interface KeyValueDiffer<K, V> { diff(object: Map<K, V>): KeyValueChanges<K, V> | null } ``` Methods ------- | diff() | | --- | | Compute a difference between the previous state and the new `object` state. | | `diff(object: Map<K, V>): KeyValueChanges<K, V> | null` Parameters | | | | | --- | --- | --- | | `object` | `Map<K, V>` | containing the new value. | Returns `[KeyValueChanges](keyvaluechanges)<K, V> | null`: an object describing the difference. The return value is only valid until the next `diff()` invocation. | | `diff(object: { [key: string]: V; }): KeyValueChanges<string, V> | null` Parameters | | | | | --- | --- | --- | | `object` | `object` | containing the new value. | Returns `[KeyValueChanges](keyvaluechanges)<string, V> | null`: an object describing the difference. The return value is only valid until the next `diff()` invocation. | angular ConstructorProvider ConstructorProvider =================== `interface` Configures the `[Injector](injector)` to return an instance of a token. ``` interface ConstructorProvider extends ConstructorSansProvider { provide: Type<any> multi?: boolean // inherited from core/ConstructorSansProvider deps?: any[] } ``` See also -------- * ["Dependency Injection Guide"](../../guide/dependency-injection). Properties ---------- | Property | Description | | --- | --- | | `provide: [Type](type)<any>` | An injection token. Typically an instance of `[Type](type)` or `[InjectionToken](injectiontoken)`, but can be `any`. | | `multi?: boolean` | When true, injector returns an array of instances. This is useful to allow multiple providers spread across many files to provide configuration information to a common token. | Usage notes ----------- ``` class Square { name = 'square'; } const injector = Injector.create({providers: [{provide: Square, deps: []}]}); const shape: Square = injector.get(Square); expect(shape.name).toEqual('square'); expect(shape instanceof Square).toBe(true); ``` ### Multi-value example ``` const locale = new InjectionToken<string[]>('locale'); const injector = Injector.create({ providers: [ {provide: locale, multi: true, useValue: 'en'}, {provide: locale, multi: true, useValue: 'sk'}, ] }); const locales: string[] = injector.get(locale); expect(locales).toEqual(['en', 'sk']); ``` angular platformCore platformCore ============ `const` This platform has to be included in any other platform ### `const platformCore: (extraProviders?: StaticProvider[]) => PlatformRef;` angular NgIterable NgIterable ========== `type-alias` A type describing supported iterable types. ``` type NgIterable<T> = Array<T> | Iterable<T>; ``` angular FactoryProvider FactoryProvider =============== `interface` Configures the `[Injector](injector)` to return a value by invoking a `useFactory` function. ``` interface FactoryProvider extends FactorySansProvider { provide: any multi?: boolean // inherited from core/FactorySansProvider useFactory: Function deps?: any[] } ``` See also -------- * ["Dependency Injection Guide"](../../guide/dependency-injection). Properties ---------- | Property | Description | | --- | --- | | `provide: any` | An injection token. (Typically an instance of `[Type](type)` or `[InjectionToken](injectiontoken)`, but can be `any`). | | `multi?: boolean` | When true, injector returns an array of instances. This is useful to allow multiple providers spread across many files to provide configuration information to a common token. | Usage notes ----------- ``` const Location = new InjectionToken('location'); const Hash = new InjectionToken('hash'); const injector = Injector.create({ providers: [ {provide: Location, useValue: 'https://angular.io/#someLocation'}, { provide: Hash, useFactory: (location: string) => location.split('#')[1], deps: [Location] } ] }); expect(injector.get(Hash)).toEqual('someLocation'); ``` Dependencies can also be marked as optional: ``` const Location = new InjectionToken('location'); const Hash = new InjectionToken('hash'); const injector = Injector.create({ providers: [{ provide: Hash, useFactory: (location: string) => `Hash for: ${location}`, // use a nested array to define metadata for dependencies. deps: [[new Optional(), Location]] }] }); expect(injector.get(Hash)).toEqual('Hash for: null'); ``` ### Multi-value example ``` const locale = new InjectionToken<string[]>('locale'); const injector = Injector.create({ providers: [ {provide: locale, multi: true, useValue: 'en'}, {provide: locale, multi: true, useValue: 'sk'}, ] }); const locales: string[] = injector.get(locale); expect(locales).toEqual(['en', 'sk']); ```
programming_docs
angular DebugNode DebugNode ========= `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` ``` class DebugNode { constructor(nativeNode: Node) nativeNode: any parent: DebugElement | null injector: Injector componentInstance: any context: any listeners: DebugEventListener[] references: {...} providerTokens: any[] } ``` Subclasses ---------- * `[DebugElement](debugelement)` Constructor ----------- | | | | | | --- | --- | --- | --- | | `constructor(nativeNode: Node)` Parameters | | | | | --- | --- | --- | | `nativeNode` | `Node` | | | Properties ---------- | Property | Description | | --- | --- | | `nativeNode: any` | Read-Only The underlying DOM node. | | `parent: [DebugElement](debugelement) | null` | Read-Only The `[DebugElement](debugelement)` parent. Will be `null` if this is the root element. | | `injector: [Injector](injector)` | Read-Only The host dependency injector. For example, the root element's component instance injector. | | `componentInstance: any` | Read-Only The element's own component instance, if it has one. | | `context: any` | Read-Only An object that provides parent context for this element. Often an ancestor component instance that governs this element. When an element is repeated within *ngFor, the context is an `[NgForOf](../common/ngforof)` whose `$implicit` property is the value of the row instance value. For example, the `hero` in `*ngFor="let hero of heroes"`. | | `listeners: [DebugEventListener](debugeventlistener)[]` | Read-Only The callbacks attached to the component's @Output properties and/or the element's event properties. | | `references: { [key: string]: any; }` | Read-Only Dictionary of objects associated with template local variables (e.g. #foo), keyed by the local variable name. | | `providerTokens: any[]` | Read-Only This component's injector lookup tokens. Includes the component itself plus the tokens that the component lists in its providers metadata. | angular Testability Testability =========== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` The Testability service provides testing hooks that can be accessed from the browser. [See more...](testability#description) ``` class Testability implements PublicTestability { increasePendingRequestCount(): number decreasePendingRequestCount(): number isStable(): boolean whenStable(doneCb: Function, timeout?: number, updateCb?: Function): void getPendingRequestCount(): number findProviders(using: any, provider: string, exactMatch: boolean): any[] } ``` Provided in ----------- * [``` ServerModule ```](../platform-server/servermodule) Description ----------- Angular applications bootstrapped using an NgModule (via `@[NgModule.bootstrap](ngmodule#bootstrap)` field) will also instantiate Testability by default (in both development and production modes). For applications bootstrapped using the `[bootstrapApplication](../platform-browser/bootstrapapplication)` function, Testability is not included by default. You can include it into your applications by getting the list of necessary providers using the `[provideProtractorTestingSupport](../platform-browser/provideprotractortestingsupport)()` function and adding them into the `options.providers` array. Example: ``` import {provideProtractorTestingSupport} from '@angular/platform-browser'; await bootstrapApplication(RootComponent, providers: [provideProtractorTestingSupport()]); ``` Methods ------- | increasePendingRequestCount() | | --- | | Increases the number of pending request | | `increasePendingRequestCount(): number` **Deprecated** pending requests are now tracked with zones. Parameters There are no parameters. Returns `number` | | decreasePendingRequestCount() | | --- | | Decreases the number of pending request | | `decreasePendingRequestCount(): number` **Deprecated** pending requests are now tracked with zones Parameters There are no parameters. Returns `number` | | isStable() | | --- | | Whether an associated application is stable | | `isStable(): boolean` Parameters There are no parameters. Returns `boolean` | | whenStable() | | --- | | Wait for the application to be stable with a timeout. If the timeout is reached before that happens, the callback receives a list of the macro tasks that were pending, otherwise null. | | `whenStable(doneCb: Function, timeout?: number, updateCb?: Function): void` Parameters | | | | | --- | --- | --- | | `doneCb` | `Function` | The callback to invoke when Angular is stable or the timeout expires whichever comes first. | | `timeout` | `number` | Optional. The maximum time to wait for Angular to become stable. If not specified, whenStable() will wait forever. Optional. Default is `undefined`. | | `updateCb` | `Function` | Optional. If specified, this callback will be invoked whenever the set of pending macrotasks changes. If this callback returns true doneCb will not be invoked and no further updates will be issued. Optional. Default is `undefined`. | Returns `void` | | getPendingRequestCount() | | --- | | Get the number of pending requests | | `getPendingRequestCount(): number` **Deprecated** pending requests are now tracked with zones Parameters There are no parameters. Returns `number` | | findProviders() | | --- | | Find providers by name | | `findProviders(using: any, provider: string, exactMatch: boolean): any[]` Parameters | | | | | --- | --- | --- | | `using` | `any` | The root element to search from | | `provider` | `string` | The name of binding variable | | `exactMatch` | `boolean` | Whether using exactMatch | Returns `any[]` | angular SimpleChanges SimpleChanges ============= `interface` A hashtable of changes represented by [`SimpleChange`](simplechange) objects stored at the declared property name they belong to on a Directive or Component. This is the type passed to the `ngOnChanges` hook. ``` interface SimpleChanges { __index(propName: string): SimpleChange } ``` See also -------- * `[OnChanges](onchanges)` Methods ------- | \_\_index() | | --- | | `__index(propName: string): SimpleChange` Parameters | | | | | --- | --- | --- | | `propName` | `string` | | Returns `[SimpleChange](simplechange)` | angular ElementRef ElementRef ========== `class` `security` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A wrapper around a native element inside of a View. [See more...](elementref#description) Security risk ------------- Permitting direct access to the DOM can make your application more vulnerable to XSS attacks. Carefully review any use of `[ElementRef](elementref)` in your code. For more detail, see the [Security Guide](https://g.co/ng/security). ``` class ElementRef<T = any> { constructor(nativeElement: T) nativeElement: T } ``` Description ----------- An `[ElementRef](elementref)` is backed by a render-specific element. In the browser, this is usually a DOM element. Constructor ----------- | | | | | | --- | --- | --- | --- | | `constructor(nativeElement: T)` Parameters | | | | | --- | --- | --- | | `nativeElement` | `T` | | | Properties ---------- | Property | Description | | --- | --- | | `nativeElement: T` | The underlying native element or `null` if direct access to native elements is not supported (e.g. when the application runs in a web worker). Use this API as the last resort when direct access to DOM is needed. Use templating and data-binding provided by Angular instead. Alternatively you can take a look at [`Renderer2`](renderer2) which provides API that can safely be used even when direct access to native elements is not supported. Relying on direct DOM access creates tight coupling between your application and rendering layers which will make it impossible to separate the two and deploy your application into a web worker. | angular destroyPlatform destroyPlatform =============== `function` Destroys the current Angular platform and all Angular applications on the page. Destroys all modules and listeners registered with the platform. ### `destroyPlatform(): void` ###### Parameters There are no parameters. ###### Returns `void` angular AfterViewChecked AfterViewChecked ================ `interface` A lifecycle hook that is called after the default change detector has completed checking a component's view for changes. ``` interface AfterViewChecked { ngAfterViewChecked(): void } ``` See also -------- * `[AfterContentChecked](aftercontentchecked)` * [Lifecycle hooks guide](../../guide/lifecycle-hooks) Methods ------- | ngAfterViewChecked() | | --- | | A callback method that is invoked immediately after the default change detector has completed one change-check cycle for a component's view. | | `ngAfterViewChecked(): void` Parameters There are no parameters. Returns `void` | Usage notes ----------- The following snippet shows how a component can implement this interface to define its own after-check functionality. ``` @Component({selector: 'my-cmp', template: `...`}) class MyComponent implements AfterViewChecked { ngAfterViewChecked() { // ... } } ``` angular GetTestability GetTestability ============== `interface` Adapter interface for retrieving the `[Testability](testability)` service associated for a particular context. ``` interface GetTestability { addToWindow(registry: TestabilityRegistry): void findTestabilityInTree(registry: TestabilityRegistry, elem: any, findInAncestors: boolean): Testability | null } ``` Methods ------- | addToWindow() | | --- | | `addToWindow(registry: TestabilityRegistry): void` Parameters | | | | | --- | --- | --- | | `registry` | `[TestabilityRegistry](testabilityregistry)` | | Returns `void` | | findTestabilityInTree() | | --- | | `findTestabilityInTree(registry: TestabilityRegistry, elem: any, findInAncestors: boolean): Testability | null` Parameters | | | | | --- | --- | --- | | `registry` | `[TestabilityRegistry](testabilityregistry)` | | | `elem` | `any` | | | `findInAncestors` | `boolean` | | Returns `[Testability](testability) | null` | angular ViewRef ViewRef ======= `class` Represents an Angular [view](../../guide/glossary#view "Definition"). ``` abstract class ViewRef extends ChangeDetectorRef { abstract destroyed: boolean abstract destroy(): void abstract onDestroy(callback: Function): any // inherited from core/ChangeDetectorRef abstract markForCheck(): void abstract detach(): void abstract detectChanges(): void abstract checkNoChanges(): void abstract reattach(): void } ``` Subclasses ---------- * `[EmbeddedViewRef](embeddedviewref)` See also -------- * [Change detection usage](changedetectorref#usage-notes) Properties ---------- | Property | Description | | --- | --- | | `abstract destroyed: boolean` | Read-Only Reports whether this view has been destroyed. | Methods ------- | destroy() | | --- | | Destroys this view and all of the data structures associated with it. | | `abstract destroy(): void` Parameters There are no parameters. Returns `void` | | onDestroy() | | --- | | A lifecycle hook that provides additional developer-defined cleanup functionality for views. | | `abstract onDestroy(callback: Function): any` Parameters | | | | | --- | --- | --- | | `callback` | `Function` | A handler function that cleans up developer-defined data associated with a view. Called when the `destroy()` method is invoked. | Returns `any` | angular HostListener HostListener ============ `decorator` Decorator that declares a DOM event to listen for, and provides a handler method to run when that event occurs. [See more...](hostlistener#description) | Option | Description | | --- | --- | | [`eventName?`](hostlistener#eventName) | The DOM event to listen for. | | [`args?`](hostlistener#args) | A set of arguments to pass to the handler method when the event occurs. | Description ----------- Angular invokes the supplied handler method when the host element emits the specified event, and updates the bound element with the result. If the handler method returns false, applies `preventDefault` on the bound element. Further information is available in the [Usage Notes...](hostlistener#usage-notes) Options ------- | eventName | | --- | | The DOM event to listen for. | | `eventName?: string` | | | | args | | --- | | A set of arguments to pass to the handler method when the event occurs. | | `args?: string[]` | | | Usage notes ----------- The following example declares a directive that attaches a click listener to a button and counts clicks. ``` @Directive({selector: 'button[counting]'}) class CountClicks { numberOfClicks = 0; @HostListener('click', ['$event.target']) onClick(btn) { console.log('button', btn, 'number of clicks:', this.numberOfClicks++); } } @Component({ selector: 'app', template: '<button counting>Increment</button>', }) class App {} ``` The following example registers another DOM event handler that listens for `Enter` key-press events on the global `window`. ``` import { HostListener, Component } from "@angular/core"; @Component({ selector: 'app', template: `<h1>Hello, you have pressed enter {{counter}} number of times!</h1> Press enter key to increment the counter. <button (click)="resetCounter()">Reset Counter</button>` }) class AppComponent { counter = 0; @HostListener('window:keydown.enter', ['$event']) handleKeyDown(event: KeyboardEvent) { this.counter++; } resetCounter() { this.counter = 0; } } ``` The list of valid key names for `keydown` and `keyup` events can be found here: <https://www.w3.org/TR/DOM-Level-3-Events-key/#named-key-attribute-values> Note that keys can also be combined, e.g. `@[HostListener](hostlistener)('keydown.shift.a')`. The global target names that can be used to prefix an event name are `document:`, `window:` and `body:`. angular DoBootstrap DoBootstrap =========== `interface` Hook for manual bootstrapping of the application instead of using `bootstrap` array in @NgModule annotation. This hook is invoked only when the `bootstrap` array is empty or not provided. [See more...](dobootstrap#description) ``` interface DoBootstrap { ngDoBootstrap(appRef: ApplicationRef): void } ``` Description ----------- Reference to the current application is provided as a parameter. See ["Bootstrapping"](../../guide/bootstrapping) and ["Entry components"](../../guide/entry-components). Further information is available in the [Usage Notes...](dobootstrap#usage-notes) Methods ------- | ngDoBootstrap() | | --- | | `ngDoBootstrap(appRef: ApplicationRef): void` Parameters | | | | | --- | --- | --- | | `appRef` | `[ApplicationRef](applicationref)` | | Returns `void` | Usage notes ----------- The example below uses `[ApplicationRef.bootstrap()](applicationref#bootstrap)` to render the `AppComponent` on the page. ``` class AppModule implements DoBootstrap { ngDoBootstrap(appRef: ApplicationRef) { appRef.bootstrap(AppComponent); // Or some other component } } ``` angular ConstructorSansProvider ConstructorSansProvider ======================= `interface` Configures the `[Injector](injector)` to return an instance of a token. ``` interface ConstructorSansProvider { deps?: any[] } ``` Child interfaces ---------------- * `[ConstructorProvider](constructorprovider)` See also -------- * ["Dependency Injection Guide"](../../guide/dependency-injection). Properties ---------- | Property | Description | | --- | --- | | `deps?: any[]` | A list of `token`s to be resolved by the injector. | Usage notes ----------- ``` @Injectable(SomeModule, {deps: []}) class MyService {} ``` angular ResolvedReflectiveFactory ResolvedReflectiveFactory ========================= `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An internal resolved representation of a factory function created by resolving `[Provider](provider)`. ``` class ResolvedReflectiveFactory { constructor(factory: Function, dependencies: ReflectiveDependency[]) factory: Function dependencies: ReflectiveDependency[] } ``` Constructor ----------- | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | | `constructor(factory: Function, dependencies: ReflectiveDependency[])` Parameters | | | | | --- | --- | --- | | `factory` | `Function` | Factory function which can return an instance of an object represented by a key. | | `dependencies` | `ReflectiveDependency[]` | Arguments (dependencies) to the `factory` function. | | Properties ---------- | Property | Description | | --- | --- | | `factory: Function` | Declared in Constructor Factory function which can return an instance of an object represented by a key. | | `dependencies: ReflectiveDependency[]` | Declared in Constructor Arguments (dependencies) to the `factory` function. | angular setTestabilityGetter setTestabilityGetter ==================== `function` Set the [`GetTestability`](gettestability) implementation used by the Angular testing framework. ### `setTestabilityGetter(getter: GetTestability): void` ###### Parameters | | | | | --- | --- | --- | | `getter` | `[GetTestability](gettestability)` | | ###### Returns `void` angular getPlatform getPlatform =========== `function` Returns the current platform. ### `getPlatform(): PlatformRef | null` ###### Parameters There are no parameters. ###### Returns `[PlatformRef](platformref) | null` angular ComponentFactory ComponentFactory ================ `class` `deprecated` Base class for a factory that can create a component dynamically. Instantiate a factory for a given type of component with `resolveComponentFactory()`. Use the resulting `ComponentFactory.create()` method to create a component of that type. **Deprecated:** Angular no longer requires Component factories. Please use other APIs where Component class can be used directly. ``` abstract class ComponentFactory<C> { abstract selector: string abstract componentType: Type<any> abstract ngContentSelectors: string[] abstract inputs: {...} abstract outputs: {...} abstract create(injector: Injector, projectableNodes?: any[][], rootSelectorOrNode?: any, environmentInjector?: EnvironmentInjector | NgModuleRef<any>): ComponentRef<C> } ``` See also -------- * [Dynamic Components](../../guide/dynamic-component-loader) Properties ---------- | Property | Description | | --- | --- | | `abstract selector: string` | Read-Only The component's HTML selector. | | `abstract componentType: [Type](type)<any>` | Read-Only The type of component the factory will create. | | `abstract ngContentSelectors: string[]` | Read-Only Selector for all elements in the component. | | `abstract inputs: { propName: string; templateName: string; }[]` | Read-Only The inputs of the component. | | `abstract outputs: { propName: string; templateName: string; }[]` | Read-Only The outputs of the component. | Methods ------- | create() | | --- | | Creates a new component. | | `abstract create(injector: Injector, projectableNodes?: any[][], rootSelectorOrNode?: any, environmentInjector?: EnvironmentInjector | NgModuleRef<any>): ComponentRef<C>` Parameters | | | | | --- | --- | --- | | `injector` | `[Injector](injector)` | | | `projectableNodes` | `any[][]` | Optional. Default is `undefined`. | | `rootSelectorOrNode` | `any` | Optional. Default is `undefined`. | | `environmentInjector` | `[EnvironmentInjector](environmentinjector) | [NgModuleRef](ngmoduleref)<any>` | Optional. Default is `undefined`. | Returns `[ComponentRef<C>](componentref)` |
programming_docs
angular HostBinding HostBinding =========== `decorator` Decorator that marks a DOM property as a host-binding property and supplies configuration metadata. Angular automatically checks host property bindings during change detection, and if a binding changes it updates the host element of the directive. | Option | Description | | --- | --- | | [`hostPropertyName?`](hostbinding#hostPropertyName) | The DOM property that is bound to a data property. | Options ------- | hostPropertyName | | --- | | The DOM property that is bound to a data property. | | `hostPropertyName?: string` | | | Usage notes ----------- The following example creates a directive that sets the `valid` and `invalid` properties on the DOM element that has an `[ngModel](../forms/ngmodel)` directive on it. ``` @Directive({selector: '[ngModel]'}) class NgModelStatus { constructor(public control: NgModel) {} @HostBinding('class.valid') get valid() { return this.control.valid; } @HostBinding('class.invalid') get invalid() { return this.control.invalid; } } @Component({ selector: 'app', template: `<input [(ngModel)]="prop">`, }) class App { prop; } ``` angular AfterViewInit AfterViewInit ============= `interface` A lifecycle hook that is called after Angular has fully initialized a component's view. Define an `ngAfterViewInit()` method to handle any additional initialization tasks. ``` interface AfterViewInit { ngAfterViewInit(): void } ``` Class implementations --------------------- * `[NgForm](../forms/ngform)` See also -------- * `[OnInit](oninit)` * `[AfterContentInit](aftercontentinit)` * [Lifecycle hooks guide](../../guide/lifecycle-hooks) Methods ------- | ngAfterViewInit() | | --- | | A callback method that is invoked immediately after Angular has completed initialization of a component's view. It is invoked only once when the view is instantiated. | | `ngAfterViewInit(): void` Parameters There are no parameters. Returns `void` | Usage notes ----------- The following snippet shows how a component can implement this interface to define its own view initialization method. ``` @Component({selector: 'my-cmp', template: `...`}) class MyComponent implements AfterViewInit { ngAfterViewInit() { // ... } } ``` angular createPlatformFactory createPlatformFactory ===================== `function` Creates a factory for a platform. Can be used to provide or override `Providers` specific to your application's runtime needs, such as `[PLATFORM\_INITIALIZER](platform_initializer)` and `[PLATFORM\_ID](platform_id)`. ### `createPlatformFactory(parentPlatformFactory: (extraProviders?: StaticProvider[]) => PlatformRef, name: string, providers: StaticProvider[] = []): (extraProviders?: StaticProvider[]) => PlatformRef` ###### Parameters | | | | | --- | --- | --- | | `parentPlatformFactory` | `(extraProviders?: [StaticProvider](staticprovider)[]) => [PlatformRef](platformref)` | Another platform factory to modify. Allows you to compose factories to build up configurations that might be required by different libraries or parts of the application. | | `name` | `string` | Identifies the new platform factory. | | `providers` | `[StaticProvider](staticprovider)[]` | A set of dependency providers for platforms created with the new factory. Optional. Default is `[]`. | ###### Returns `(extraProviders?: [StaticProvider](staticprovider)[]) => [PlatformRef](platformref)` angular Inject Inject ====== `decorator` Parameter decorator on a dependency parameter of a class constructor that specifies a custom provider of the dependency. | Option | Description | | --- | --- | | [`token`](inject#token) | A [DI token](../../guide/glossary#di-token) that maps to the dependency to be injected. | See also -------- * ["Dependency Injection Guide"](../../guide/dependency-injection) Options ------- | token | | --- | | A [DI token](../../guide/glossary#di-token) that maps to the dependency to be injected. | | `token: any` | | | Usage notes ----------- The following example shows a class constructor that specifies a custom provider of a dependency using the parameter decorator. When `@[Inject](inject)()` is not present, the injector uses the type annotation of the parameter as the provider. ``` class Engine {} @Injectable() class Car { constructor(public engine: Engine) { } // same as constructor(@Inject(Engine) engine:Engine) } const injector = Injector.create( {providers: [{provide: Engine, deps: []}, {provide: Car, deps: [Engine]}]}); expect(injector.get(Car).engine instanceof Engine).toBe(true); ``` angular TRANSLATIONS_FORMAT TRANSLATIONS\_FORMAT ==================== `const` Provide this token at bootstrap to set the format of your [`TRANSLATIONS`](translations): `xtb`, `xlf` or `xlf2`. [See more...](translations_format#description) ### `const TRANSLATIONS_FORMAT: InjectionToken<string>;` #### Description See the [i18n guide](../../guide/i18n-common-merge) for more information. Further information is available in the [Usage Notes...](translations_format#usage-notes) Usage notes ----------- #### Example ``` import { TRANSLATIONS_FORMAT } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; platformBrowserDynamic().bootstrapModule(AppModule, { providers: [{provide: TRANSLATIONS_FORMAT, useValue: 'xlf' }] }); ``` angular Type Type ==== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Represents a type that a Component or other object is instances of. [See more...](type#description) ``` class Type<T> extends Function { constructor(...args: any[]): T } ``` Description ----------- An example of a `[Type](type)` is `MyCustomComponent` class, which in JavaScript is represented by the `MyCustomComponent` constructor function. Constructor ----------- | | | | | | --- | --- | --- | --- | | `constructor(...args: any[]): T` Parameters | | | | | --- | --- | --- | | `args` | `any[]` | | Returns `T` | angular Optional Optional ======== `decorator` Parameter decorator to be used on constructor parameters, which marks the parameter as being an optional dependency. The DI framework provides `null` if the dependency is not found. [See more...](optional#description) See also -------- * ["Dependency Injection Guide"](../../guide/dependency-injection). Description ----------- Can be used together with other parameter decorators that modify how dependency injection operates. Further information is available in the [Usage Notes...](optional#usage-notes) Options ------- Usage notes ----------- The following code allows the possibility of a `null` result: ``` class Engine {} @Injectable() class Car { constructor(@Optional() public engine: Engine) {} } const injector = Injector.create({providers: [{provide: Car, deps: [[new Optional(), Engine]]}]}); expect(injector.get(Car).engine).toBeNull(); ``` angular NgProbeToken NgProbeToken ============ `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A token for third-party components that can register themselves with NgProbe. ``` class NgProbeToken { constructor(name: string, token: any) name: string token: any } ``` Constructor ----------- | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | | `constructor(name: string, token: any)` Parameters | | | | | --- | --- | --- | | `name` | `string` | | | `token` | `any` | | | Properties ---------- | Property | Description | | --- | --- | | `name: string` | Declared in Constructor | | `token: any` | Declared in Constructor | angular InjectFlags InjectFlags =========== `enum` `deprecated` Injection flags for DI. **Deprecated:** use an options object for `inject` instead. ``` enum InjectFlags { Default: 0b0000 Host: 0b0001 Self: 0b0010 SkipSelf: 0b0100 Optional: 0b1000 } ``` Members ------- | Member | Description | | --- | --- | | `Default: 0b0000` | Check self and check parent injector if needed | | `[Host](host): 0b0001` | Specifies that an injector should retrieve a dependency from any injector until reaching the host element of the current component. (Only used with Element Injector) | | `[Self](self): 0b0010` | Don't ascend to ancestors of the node requesting injection. | | `[SkipSelf](skipself): 0b0100` | Skip the node that is requesting injection. | | `[Optional](optional): 0b1000` | Inject `defaultValue` instead if token not found. | angular ComponentMirror ComponentMirror =============== `interface` An interface that describes the subset of component metadata that can be retrieved using the `[reflectComponentType](reflectcomponenttype)` function. ``` interface ComponentMirror<C> { selector: string type: Type<C> inputs: ReadonlyArray<{...} outputs: ReadonlyArray<{...} ngContentSelectors: ReadonlyArray<string> isStandalone: boolean } ``` Properties ---------- | Property | Description | | --- | --- | | `selector: string` | Read-Only The component's HTML selector. | | `type: [Type](type)<C>` | Read-Only The type of component the factory will create. | | `inputs: ReadonlyArray<{ readonly propName: string; readonly templateName: string; }>` | Read-Only The inputs of the component. | | `outputs: ReadonlyArray<{ readonly propName: string; readonly templateName: string; }>` | Read-Only The outputs of the component. | | `ngContentSelectors: ReadonlyArray<string>` | Read-Only Selector for all elements in the component. | | `[isStandalone](isstandalone): boolean` | Read-Only Whether this component is marked as standalone. Note: an extra flag, not present in `[ComponentFactory](componentfactory)`. | angular makeEnvironmentProviders makeEnvironmentProviders ======================== `function` Wrap an array of `[Provider](provider)`s into `[EnvironmentProviders](environmentproviders)`, preventing them from being accidentally referenced in `@Component in a component injector. ### `makeEnvironmentProviders(providers: (Provider | EnvironmentProviders)[]): EnvironmentProviders` ###### Parameters | | | | | --- | --- | --- | | `providers` | `([Provider](provider) | [EnvironmentProviders](environmentproviders))[]` | | ###### Returns `[EnvironmentProviders](environmentproviders)` angular ContentChildren ContentChildren =============== `decorator` Property decorator that configures a content query. [See more...](contentchildren#description) Description ----------- Use to get the `[QueryList](querylist)` of elements or directives from the content DOM. Any time a child element is added, removed, or moved, the query list will be updated, and the changes observable of the query list will emit a new value. Content queries are set before the `ngAfterContentInit` callback is called. Does not retrieve elements or directives that are in other components' templates, since a component's template is always a black box to its ancestors. **Metadata Properties**: * **selector** - The directive type or the name used for querying. * **descendants** - If `true` include all descendants of the element. If `false` then only query direct children of the element. * **emitDistinctChangesOnly** - The `[QueryList](querylist)#changes` observable will emit new values only if the QueryList result has changed. When `false` the `changes` observable might emit even if the QueryList has not changed. **Note: \*** This config option is **deprecated**, it will be permanently set to `true` and removed in future versions of Angular. * **read** - Used to read a different token from the queried elements. The following selectors are supported. * Any class with the `@[Component](component)` or `@[Directive](directive)` decorator * A template reference variable as a string (e.g. query `<my-component #cmp></my-component>` with `@[ContentChildren](contentchildren)('cmp')`) * Any provider defined in the child component tree of the current component (e.g. `@[ContentChildren](contentchildren)(SomeService) someService: SomeService`) * Any provider defined through a string token (e.g. `@[ContentChildren](contentchildren)('someToken') someTokenVal: any`) * A `[TemplateRef](templateref)` (e.g. query `<ng-template></ng-template>` with `@[ContentChildren](contentchildren)([TemplateRef](templateref)) template;`) In addition, multiple string selectors can be separated with a comma (e.g. `@[ContentChildren](contentchildren)('cmp1,cmp2')`) The following values are supported by `read`: * Any class with the `@[Component](component)` or `@[Directive](directive)` decorator * Any provider defined on the injector of the component that is matched by the `selector` of this query * Any provider defined through a string token (e.g. `{provide: 'token', useValue: 'val'}`) * `[TemplateRef](templateref)`, `[ElementRef](elementref)`, and `[ViewContainerRef](viewcontainerref)` Further information is available in the [Usage Notes...](contentchildren#usage-notes) Options ------- Usage notes ----------- Here is a simple demonstration of how the `[ContentChildren](contentchildren)` decorator can be used. ``` import {AfterContentInit, ContentChildren, Directive, QueryList} from '@angular/core'; @Directive({selector: 'child-directive'}) class ChildDirective { } @Directive({selector: 'someDir'}) class SomeDir implements AfterContentInit { @ContentChildren(ChildDirective) contentChildren!: QueryList<ChildDirective>; ngAfterContentInit() { // contentChildren is set } } ``` ### Tab-pane example Here is a slightly more realistic example that shows how `[ContentChildren](contentchildren)` decorators can be used to implement a tab pane component. ``` import {Component, ContentChildren, Directive, Input, QueryList} from '@angular/core'; @Directive({selector: 'pane'}) export class Pane { @Input() id!: string; } @Component({ selector: 'tab', template: ` <div class="top-level">Top level panes: {{serializedPanes}}</div> <div class="nested">Arbitrary nested panes: {{serializedNestedPanes}}</div> ` }) export class Tab { @ContentChildren(Pane) topLevelPanes!: QueryList<Pane>; @ContentChildren(Pane, {descendants: true}) arbitraryNestedPanes!: QueryList<Pane>; get serializedPanes(): string { return this.topLevelPanes ? this.topLevelPanes.map(p => p.id).join(', ') : ''; } get serializedNestedPanes(): string { return this.arbitraryNestedPanes ? this.arbitraryNestedPanes.map(p => p.id).join(', ') : ''; } } @Component({ selector: 'example-app', template: ` <tab> <pane id="1"></pane> <pane id="2"></pane> <pane id="3" *ngIf="shouldShow"> <tab> <pane id="3_1"></pane> <pane id="3_2"></pane> </tab> </pane> </tab> <button (click)="show()">Show 3</button> `, }) export class ContentChildrenComp { shouldShow = false; show() { this.shouldShow = true; } } ``` angular PLATFORM_ID PLATFORM\_ID ============ `const` A token that indicates an opaque platform ID. ### `const PLATFORM_ID: InjectionToken<Object>;` angular PLATFORM_INITIALIZER PLATFORM\_INITIALIZER ===================== `const` A function that is executed when a platform is initialized. ### `const PLATFORM_INITIALIZER: InjectionToken<(() => void)[]>;` angular DebugElement DebugElement ============ `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` ``` class DebugElement extends DebugNode { constructor(nativeNode: Element) nativeElement: any name: string properties: {...} attributes: {...} styles: {...} classes: {...} childNodes: DebugNode[] children: DebugElement[] query(predicate: Predicate<DebugElement>): DebugElement queryAll(predicate: Predicate<DebugElement>): DebugElement[] queryAllNodes(predicate: Predicate<DebugNode>): DebugNode[] triggerEventHandler(eventName: string, eventObj?: any): void // inherited from core/DebugNode constructor(nativeNode: Node) nativeNode: any parent: DebugElement | null injector: Injector componentInstance: any context: any listeners: DebugEventListener[] references: {...} providerTokens: any[] } ``` See also -------- * [Component testing scenarios](../../guide/testing-components-scenarios) * [Basics of testing components](../../guide/testing-components-basics) * [Testing utility APIs](../../guide/testing-utility-apis) Constructor ----------- | | | | | | --- | --- | --- | --- | | `constructor(nativeNode: Element)` Parameters | | | | | --- | --- | --- | | `nativeNode` | `Element` | | | Properties ---------- | Property | Description | | --- | --- | | `nativeElement: any` | Read-Only The underlying DOM element at the root of the component. | | `name: string` | Read-Only The element tag name, if it is an element. | | `properties: { [key: string]: any; }` | Read-Only Gets a map of property names to property values for an element. This map includes:* Regular property bindings (e.g. `[id]="id"`) * Host property bindings (e.g. `host: { '[id]': "id" }`) * Interpolated property bindings (e.g. `id="{{ value }}") It does not include: * input property bindings (e.g. `[myCustomInput]="value"`) * attribute bindings (e.g. `[attr.role]="menu"`) | | `attributes: { [key: string]: string | null; }` | Read-Only A map of attribute names to attribute values for an element. | | `styles: { [key: string]: string | null; }` | Read-Only The inline styles of the DOM element. Will be `null` if there is no `[style](../animations/style)` property on the underlying DOM element. See also:* [ElementCSSInlineStyle](https://developer.mozilla.org/en-US/docs/Web/API/ElementCSSInlineStyle/style) | | `classes: { [key: string]: boolean; }` | Read-Only A map containing the class names on the element as keys. This map is derived from the `className` property of the DOM element. Note: The values of this object will always be `true`. The class key will not appear in the KV object if it does not exist on the element. See also:* [Element.className](https://developer.mozilla.org/en-US/docs/Web/API/Element/className) | | `childNodes: [DebugNode](debugnode)[]` | Read-Only The `childNodes` of the DOM element as a `[DebugNode](debugnode)` array. See also:* [Node.childNodes](https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes) | | `children: [DebugElement](debugelement)[]` | Read-Only The immediate `[DebugElement](debugelement)` children. Walk the tree by descending through `children`. | Methods ------- | query() | | --- | | `query(predicate: Predicate<DebugElement>): DebugElement` Parameters | | | | | --- | --- | --- | | `predicate` | `[Predicate](predicate)<[DebugElement](debugelement)>` | | Returns `[DebugElement](debugelement)`: the first `[DebugElement](debugelement)` that matches the predicate at any depth in the subtree. | | queryAll() | | --- | | `queryAll(predicate: Predicate<DebugElement>): DebugElement[]` Parameters | | | | | --- | --- | --- | | `predicate` | `[Predicate](predicate)<[DebugElement](debugelement)>` | | Returns `[DebugElement](debugelement)[]`: All `[DebugElement](debugelement)` matches for the predicate at any depth in the subtree. | | queryAllNodes() | | --- | | `queryAllNodes(predicate: Predicate<DebugNode>): DebugNode[]` Parameters | | | | | --- | --- | --- | | `predicate` | `[Predicate](predicate)<[DebugNode](debugnode)>` | | Returns `[DebugNode](debugnode)[]`: All `[DebugNode](debugnode)` matches for the predicate at any depth in the subtree. | | triggerEventHandler() | | --- | | Triggers the event by its name if there is a corresponding listener in the element's `listeners` collection. See also:* [Testing components scenarios](../../guide/testing-components-scenarios#trigger-event-handler) | | `triggerEventHandler(eventName: string, eventObj?: any): void` Parameters | | | | | --- | --- | --- | | `eventName` | `string` | The name of the event to trigger | | `eventObj` | `any` | The *event object* expected by the handler Optional. Default is `undefined`. | Returns `void` | | If the event lacks a listener or there's some other problem, consider calling `nativeElement.dispatchEvent(eventObject)`. |
programming_docs
angular ApplicationInitStatus ApplicationInitStatus ===================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A class that reflects the state of running [`APP_INITIALIZER`](app_initializer) functions. ``` class ApplicationInitStatus { donePromise: Promise<any> done: false } ``` Provided in ----------- * ``` 'root' ``` Properties ---------- | Property | Description | | --- | --- | | `donePromise: Promise<any>` | Read-Only | | `done: false` | Read-Only | angular Provider Provider ======== `type-alias` Describes how the `[Injector](injector)` should be configured. ``` type Provider = TypeProvider | ValueProvider | ClassProvider | ConstructorProvider | ExistingProvider | FactoryProvider | any[]; ``` See also -------- * ["Dependency Injection Guide"](../../guide/dependency-injection). * `[StaticProvider](staticprovider)` angular EnvironmentInjector EnvironmentInjector =================== `class` An `[Injector](injector)` that's part of the environment injector hierarchy, which exists outside of the component tree. ``` abstract class EnvironmentInjector implements Injector { abstract get<T>(token: ProviderToken<T>, notFoundValue: undefined, options: InjectOptions & { optional?: false; }): T abstract runInContext<ReturnT>(fn: () => ReturnT): ReturnT abstract destroy(): void } ``` Methods ------- | get() | | --- | | Retrieves an instance from the injector based on the provided token. | | 4 overloads... Show All Hide All `abstract get<T>(token: ProviderToken<T>, notFoundValue: undefined, options: InjectOptions & { optional?: false; }): T` Parameters | | | | | --- | --- | --- | | `token` | `[ProviderToken](providertoken)<T>` | | | `notFoundValue` | `undefined` | | | `options` | `[InjectOptions](injectoptions) & { optional?: false; }` | | Returns `T`: The instance from the injector if defined, otherwise the `notFoundValue`. Throws `Error` When the `notFoundValue` is `undefined` or `[Injector.THROW\_IF\_NOT\_FOUND](injector#THROW_IF_NOT_FOUND)`. Overload #1 `abstract get<T>(token: ProviderToken<T>, notFoundValue: null, options: InjectOptions): T | null` Parameters | | | | | --- | --- | --- | | `token` | `[ProviderToken](providertoken)<T>` | | | `notFoundValue` | `null` | | | `options` | `[InjectOptions](injectoptions)` | | Returns `T | null`: The instance from the injector if defined, otherwise the `notFoundValue`. Throws `Error` When the `notFoundValue` is `undefined` or `[Injector.THROW\_IF\_NOT\_FOUND](injector#THROW_IF_NOT_FOUND)`. Overload #2 `abstract get<T>(token: ProviderToken<T>, notFoundValue?: T, options?: InjectOptions): T` Parameters | | | | | --- | --- | --- | | `token` | `[ProviderToken](providertoken)<T>` | | | `notFoundValue` | `T` | Optional. Default is `undefined`. | | `options` | `[InjectOptions](injectoptions)` | Optional. Default is `undefined`. | Returns `T`: The instance from the injector if defined, otherwise the `notFoundValue`. Throws `Error` When the `notFoundValue` is `undefined` or `[Injector.THROW\_IF\_NOT\_FOUND](injector#THROW_IF_NOT_FOUND)`. Overload #3 `abstract get<T>(token: ProviderToken<T>, notFoundValue?: T, flags?: InjectFlags): T` **Deprecated** use object-based flags (`[InjectOptions](injectoptions)`) instead. Parameters | | | | | --- | --- | --- | | `token` | `[ProviderToken](providertoken)<T>` | | | `notFoundValue` | `T` | Optional. Default is `undefined`. | | `flags` | `[InjectFlags](injectflags)` | Optional. Default is `undefined`. | Returns `T`: The instance from the injector if defined, otherwise the `notFoundValue`. Throws `Error` When the `notFoundValue` is `undefined` or `[Injector.THROW\_IF\_NOT\_FOUND](injector#THROW_IF_NOT_FOUND)`. Overload #4 `abstract get(token: any, notFoundValue?: any): any` **Deprecated** from v4.0.0 use ProviderToken Parameters | | | | | --- | --- | --- | | `token` | `any` | | | `notFoundValue` | `any` | Optional. Default is `undefined`. | Returns `any` | | runInContext() | | --- | | Runs the given function in the context of this `[EnvironmentInjector](environmentinjector)`. | | `abstract runInContext<ReturnT>(fn: () => ReturnT): ReturnT` Parameters | | | | | --- | --- | --- | | `fn` | `() => ReturnT` | the closure to be run in the context of this injector | Returns `ReturnT`: the return value of the function, if any | | Within the function's stack frame, `inject` can be used to inject dependencies from this injector. Note that `inject` is only usable synchronously, and cannot be used in any asynchronous callbacks or after any `await` points. | | destroy() | | --- | | `abstract destroy(): void` Parameters There are no parameters. Returns `void` | angular CompilerFactory CompilerFactory =============== `class` `deprecated` A factory for creating a Compiler **Deprecated:** Ivy JIT mode doesn't require accessing this symbol. See [JIT API changes due to ViewEngine deprecation](../../guide/deprecations#jit-api-changes) for additional context. ``` abstract class CompilerFactory { abstract createCompiler(options?: CompilerOptions[]): Compiler } ``` Subclasses ---------- * `[JitCompilerFactory](../platform-browser-dynamic/jitcompilerfactory)` Methods ------- | createCompiler() | | --- | | `abstract createCompiler(options?: CompilerOptions[]): Compiler` Parameters | | | | | --- | --- | --- | | `options` | `[CompilerOptions](compileroptions)[]` | Optional. Default is `undefined`. | Returns `[Compiler](compiler)` | angular ModuleWithProviders ModuleWithProviders =================== `interface` A wrapper around an NgModule that associates it with [providers](../../guide/glossary#provider "Definition"). Usage without a generic type is deprecated. ``` interface ModuleWithProviders<T> { ngModule: Type<T> providers?: Array<Provider | EnvironmentProviders> } ``` See also -------- * [Deprecations](../../guide/deprecations#modulewithproviders-type-without-a-generic) Properties ---------- | Property | Description | | --- | --- | | `ngModule: [Type](type)<T>` | | | `providers?: Array<[Provider](provider) | [EnvironmentProviders](environmentproviders)>` | | angular KeyValueDifferFactory KeyValueDifferFactory ===================== `interface` Provides a factory for [`KeyValueDiffer`](keyvaluediffer). ``` interface KeyValueDifferFactory { supports(objects: any): boolean create<K, V>(): KeyValueDiffer<K, V> } ``` Methods ------- | supports() | | --- | | Test to see if the differ knows how to diff this kind of object. | | `supports(objects: any): boolean` Parameters | | | | | --- | --- | --- | | `objects` | `any` | | Returns `boolean` | | create() | | --- | | Create a `[KeyValueDiffer](keyvaluediffer)`. | | `create<K, V>(): KeyValueDiffer<K, V>` Parameters There are no parameters. Returns `[KeyValueDiffer<K, V>](keyvaluediffer)` | angular <ng-content> <ng-content> ============ `element` The `[<ng-content>](ng-content)` element specifies where to project content inside a component template. [See more...](ng-content#description) Description ----------- @elementAttribute select="selector" Only select elements from the projected content that match the given CSS `selector`. angular PipeTransform PipeTransform ============= `interface` An interface that is implemented by pipes in order to perform a transformation. Angular invokes the `transform` method with the value of a binding as the first argument, and any parameters as the second argument in list form. ``` interface PipeTransform { transform(value: any, ...args: any[]): any } ``` Class implementations --------------------- * `[AsyncPipe](../common/asyncpipe)` * `[DatePipe](../common/datepipe)` * `[I18nPluralPipe](../common/i18npluralpipe)` * `[I18nSelectPipe](../common/i18nselectpipe)` * `[JsonPipe](../common/jsonpipe)` * `[LowerCasePipe](../common/lowercasepipe)` * `[CurrencyPipe](../common/currencypipe)` * `[DecimalPipe](../common/decimalpipe)` * `[PercentPipe](../common/percentpipe)` * `[SlicePipe](../common/slicepipe)` * `[UpperCasePipe](../common/uppercasepipe)` * `[TitleCasePipe](../common/titlecasepipe)` * `[KeyValuePipe](../common/keyvaluepipe)` Methods ------- | transform() | | --- | | `transform(value: any, ...args: any[]): any` Parameters | | | | | --- | --- | --- | | `value` | `any` | | | `args` | `any[]` | | Returns `any` | Usage notes ----------- In the following example, `TruncatePipe` returns the shortened value with an added ellipses. ``` import {Pipe, PipeTransform} from '@angular/core'; @Pipe({name: 'truncate'}) export class TruncatePipe implements PipeTransform { transform(value: string) { return value.split(' ').slice(0, 2).join(' ') + '...'; } } ``` Invoking `{{ 'It was the best of times' | truncate }}` in a template will produce `It was...`. In the following example, `TruncatePipe` takes parameters that sets the truncated length and the string to append with. ``` import {Pipe, PipeTransform} from '@angular/core'; @Pipe({name: 'truncate'}) export class TruncatePipe implements PipeTransform { transform(value: string, length: number, symbol: string) { return value.split(' ').slice(0, length).join(' ') + symbol; } } ``` Invoking `{{ 'It was the best of times' | truncate:4:'....' }}` in a template will produce `It was the best....`. angular @angular/core/global @angular/core/global ==================== `entry-point` Exposes a set of functions in the global namespace which are useful for debugging the current state of your application. These functions are exposed via the global `ng` "namespace" variable automatically when you import from `@angular/core` and run your application in development mode. These functions are not exposed when the application runs in a production mode. Entry point exports ------------------- ### Functions | | | | --- | --- | | `[ng.applyChanges](global/ngapplychanges)` | Marks a component for check (in case of OnPush components) and synchronously performs change detection on the application this component belongs to. | | `[ng.getComponent](global/nggetcomponent)` | Retrieves the component instance associated with a given DOM element. | | `[ng.getContext](global/nggetcontext)` | If inside an embedded view (e.g. `*[ngIf](../common/ngif)` or `*[ngFor](../common/ngfor)`), retrieves the context of the embedded view that the element is part of. Otherwise retrieves the instance of the component whose view owns the element (in this case, the result is the same as calling `[getOwningComponent](global/nggetowningcomponent)`). | | `[ng.getDirectiveMetadata](global/nggetdirectivemetadata)` | Returns the debug (partial) metadata for a particular directive or component instance. The function accepts an instance of a directive or component and returns the corresponding metadata. | | `[ng.getDirectives](global/nggetdirectives)` | Retrieves directive instances associated with a given DOM node. Does not include component instances. | | `[ng.getHostElement](global/nggethostelement)` | Retrieves the host element of a component or directive instance. The host element is the DOM element that matched the selector of the directive. | | `[ng.getInjector](global/nggetinjector)` | Retrieves an `[Injector](injector)` associated with an element, component or directive instance. | | `[ng.getListeners](global/nggetlisteners)` | Retrieves a list of event listeners associated with a DOM element. The list does include host listeners, but it does not include event listeners defined outside of the Angular context (e.g. through `addEventListener`). | | `[ng.getOwningComponent](global/nggetowningcomponent)` | Retrieves the component instance whose view contains the DOM element. | | `[ng.getRootComponents](global/nggetrootcomponents)` | Retrieves all root components associated with a DOM element, directive or component instance. Root components are those which have been bootstrapped by Angular. | ### Structures | | | | --- | --- | | `[ComponentDebugMetadata](global/componentdebugmetadata)` | Partial metadata for a given component instance. This information might be useful for debugging purposes or tooling. Currently the following fields are available:* inputs * outputs * encapsulation * changeDetection | | `[DirectiveDebugMetadata](global/directivedebugmetadata)` | Partial metadata for a given directive instance. This information might be useful for debugging purposes or tooling. Currently only `inputs` and `outputs` metadata is available. | | `[Listener](global/listener)` | Event listener configuration returned from `[getListeners](global/nggetlisteners)`. | angular ANIMATION_MODULE_TYPE ANIMATION\_MODULE\_TYPE ======================= `const` A [DI token](../../guide/glossary#di-token "DI token definition") that indicates which animations module has been loaded. ### `const ANIMATION_MODULE_TYPE: InjectionToken<"NoopAnimations" | "BrowserAnimations">;` angular RendererStyleFlags2 RendererStyleFlags2 =================== `enum` Flags for renderer-specific style modifiers. ``` enum RendererStyleFlags2 { Important: 1 << 0 DashCase: 1 << 1 } ``` Members ------- | Member | Description | | --- | --- | | `Important: 1 << 0` | Marks a style as important. | | `DashCase: 1 << 1` | Marks a style as using dash case naming (this-is-dash-case). | angular OnInit OnInit ====== `interface` A lifecycle hook that is called after Angular has initialized all data-bound properties of a directive. Define an `ngOnInit()` method to handle any additional initialization tasks. ``` interface OnInit { ngOnInit(): void } ``` Class implementations --------------------- * `[NgOptimizedImage](../common/ngoptimizedimage)` * `[AbstractFormGroupDirective](../forms/abstractformgroupdirective)` + `[NgModelGroup](../forms/ngmodelgroup)` + `[FormGroupName](../forms/formgroupname)` * `[NgModelGroup](../forms/ngmodelgroup)` * `[RadioControlValueAccessor](../forms/radiocontrolvalueaccessor)` * `[FormArrayName](../forms/formarrayname)` * `[FormGroupName](../forms/formgroupname)` * `[RouterOutlet](../router/routeroutlet)` * `[UpgradeComponent](../upgrade/static/upgradecomponent)` See also -------- * `[AfterContentInit](aftercontentinit)` * [Lifecycle hooks guide](../../guide/lifecycle-hooks) Methods ------- | ngOnInit() | | --- | | A callback method that is invoked immediately after the default change detector has checked the directive's data-bound properties for the first time, and before any of the view or content children have been checked. It is invoked only once when the directive is instantiated. | | `ngOnInit(): void` Parameters There are no parameters. Returns `void` | Usage notes ----------- The following snippet shows how a component can implement this interface to define its own initialization method. ``` @Component({selector: 'my-cmp', template: `...`}) class MyComponent implements OnInit { ngOnInit() { // ... } } ``` angular MissingTranslationStrategy MissingTranslationStrategy ========================== `enum` Use this enum at bootstrap as an option of `bootstrapModule` to define the strategy that the compiler should use in case of missing translations: * Error: throw if you have missing translations. * Warning (default): show a warning in the console and/or shell. * Ignore: do nothing. [See more...](missingtranslationstrategy#description) ``` enum MissingTranslationStrategy { Error: 0 Warning: 1 Ignore: 2 } ``` Description ----------- See the [i18n guide](../../guide/i18n-common-merge#report-missing-translations) for more information. Further information is available in the [Usage Notes...](missingtranslationstrategy#usage-notes) Members ------- | Member | Description | | --- | --- | | `Error: 0` | | | `Warning: 1` | | | `Ignore: 2` | | Usage notes ----------- ### Example ``` import { MissingTranslationStrategy } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; platformBrowserDynamic().bootstrapModule(AppModule, { missingTranslation: MissingTranslationStrategy.Error }); ``` angular assertPlatform assertPlatform ============== `function` Checks that there is currently a platform that contains the given token as a provider. ### `assertPlatform(requiredToken: any): PlatformRef` ###### Parameters | | | | | --- | --- | --- | | `requiredToken` | `any` | | ###### Returns `[PlatformRef](platformref)` angular IterableDiffers IterableDiffers =============== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A repository of different iterable diffing strategies used by NgFor, NgClass, and others. ``` class IterableDiffers { static create(factories: IterableDifferFactory[], parent?: IterableDiffers): IterableDiffers static extend(factories: IterableDifferFactory[]): StaticProvider constructor(factories: IterableDifferFactory[]) factories: IterableDifferFactory[] find(iterable: any): IterableDifferFactory } ``` Provided in ----------- * ``` 'root' ``` Static methods -------------- | create() | | --- | | `static create(factories: IterableDifferFactory[], parent?: IterableDiffers): IterableDiffers` Parameters | | | | | --- | --- | --- | | `factories` | `[IterableDifferFactory](iterabledifferfactory)[]` | | | `parent` | `[IterableDiffers](iterablediffers)` | Optional. Default is `undefined`. | Returns `[IterableDiffers](iterablediffers)` | | extend() | | --- | | Takes an array of [`IterableDifferFactory`](iterabledifferfactory) and returns a provider used to extend the inherited [`IterableDiffers`](iterablediffers) instance with the provided factories and return a new [`IterableDiffers`](iterablediffers) instance. | | `static extend(factories: IterableDifferFactory[]): StaticProvider` Parameters | | | | | --- | --- | --- | | `factories` | `[IterableDifferFactory](iterabledifferfactory)[]` | | Returns `[StaticProvider](staticprovider)` | | Usage Notes Example The following example shows how to extend an existing list of factories, which will only be applied to the injector for this component and its children. This step is all that's required to make a new [`IterableDiffer`](iterablediffer) available. ``` @Component({ viewProviders: [ IterableDiffers.extend([new ImmutableListDiffer()]) ] }) ``` | Constructor ----------- | | | | | | --- | --- | --- | --- | | `constructor(factories: IterableDifferFactory[])` Parameters | | | | | --- | --- | --- | | `factories` | `[IterableDifferFactory](iterabledifferfactory)[]` | | | Properties ---------- | Property | Description | | --- | --- | | `factories: [IterableDifferFactory](iterabledifferfactory)[]` | **Deprecated** v4.0.0 - Should be private | Methods ------- | find() | | --- | | `find(iterable: any): IterableDifferFactory` Parameters | | | | | --- | --- | --- | | `iterable` | `any` | | Returns `[IterableDifferFactory](iterabledifferfactory)` | angular ReflectiveInjector ReflectiveInjector ================== `class` `deprecated` A ReflectiveDependency injection container used for instantiating objects and resolving dependencies. [See more...](reflectiveinjector#description) **Deprecated:** from v5 - slow and brings in a lot of code, Use `Injector.create` instead. ``` abstract class ReflectiveInjector implements Injector { static resolve(providers: Provider[]): ResolvedReflectiveProvider[] static resolveAndCreate(providers: Provider[], parent?: Injector): ReflectiveInjector static fromResolvedProviders(providers: ResolvedReflectiveProvider[], parent?: Injector): ReflectiveInjector abstract parent: Injector | null abstract resolveAndCreateChild(providers: Provider[]): ReflectiveInjector abstract createChildFromResolved(providers: ResolvedReflectiveProvider[]): ReflectiveInjector abstract resolveAndInstantiate(provider: Provider): any abstract instantiateResolved(provider: ResolvedReflectiveProvider): any abstract get(token: any, notFoundValue?: any): any } ``` Description ----------- An `[Injector](injector)` is a replacement for a `new` operator, which can automatically resolve the constructor dependencies. In typical use, application code asks for the dependencies in the constructor and they are resolved by the `[Injector](injector)`. Further information is available in the [Usage Notes...](reflectiveinjector#usage-notes) Static methods -------------- | resolve() | | --- | | Turns an array of provider definitions into an array of resolved providers. | | `static resolve(providers: Provider[]): ResolvedReflectiveProvider[]` Parameters | | | | | --- | --- | --- | | `providers` | `[Provider](provider)[]` | | Returns `[ResolvedReflectiveProvider](resolvedreflectiveprovider)[]` | | A resolution is a process of flattening multiple nested arrays and converting individual providers into an array of `[ResolvedReflectiveProvider](resolvedreflectiveprovider)`s. | | Usage Notes Example ``` @Injectable() class Engine { } @Injectable() class Car { constructor(public engine:Engine) {} } var providers = ReflectiveInjector.resolve([Car, [[Engine]]]); expect(providers.length).toEqual(2); expect(providers[0] instanceof ResolvedReflectiveProvider).toBe(true); expect(providers[0].key.displayName).toBe("Car"); expect(providers[0].dependencies.length).toEqual(1); expect(providers[0].factory).toBeDefined(); expect(providers[1].key.displayName).toBe("Engine"); }); ``` | | resolveAndCreate() | | --- | | Resolves an array of providers and creates an injector from those providers. | | `static resolveAndCreate(providers: Provider[], parent?: Injector): ReflectiveInjector` Parameters | | | | | --- | --- | --- | | `providers` | `[Provider](provider)[]` | | | `parent` | `[Injector](injector)` | Optional. Default is `undefined`. | Returns `[ReflectiveInjector](reflectiveinjector)` | | The passed-in providers can be an array of `[Type](type)`, `[Provider](provider)`, or a recursive array of more providers. | | Usage Notes Example ``` @Injectable() class Engine { } @Injectable() class Car { constructor(public engine:Engine) {} } var injector = ReflectiveInjector.resolveAndCreate([Car, Engine]); expect(injector.get(Car) instanceof Car).toBe(true); ``` | | fromResolvedProviders() | | --- | | Creates an injector from previously resolved providers. | | `static fromResolvedProviders(providers: ResolvedReflectiveProvider[], parent?: Injector): ReflectiveInjector` Parameters | | | | | --- | --- | --- | | `providers` | `[ResolvedReflectiveProvider](resolvedreflectiveprovider)[]` | | | `parent` | `[Injector](injector)` | Optional. Default is `undefined`. | Returns `[ReflectiveInjector](reflectiveinjector)` | | This API is the recommended way to construct injectors in performance-sensitive parts. | | Usage Notes Example ``` @Injectable() class Engine { } @Injectable() class Car { constructor(public engine:Engine) {} } var providers = ReflectiveInjector.resolve([Car, Engine]); var injector = ReflectiveInjector.fromResolvedProviders(providers); expect(injector.get(Car) instanceof Car).toBe(true); ``` | Properties ---------- | Property | Description | | --- | --- | | `abstract parent: [Injector](injector) | null` | Read-Only Parent of this injector. | Methods ------- | resolveAndCreateChild() | | --- | | Resolves an array of providers and creates a child injector from those providers. | | `abstract resolveAndCreateChild(providers: Provider[]): ReflectiveInjector` Parameters | | | | | --- | --- | --- | | `providers` | `[Provider](provider)[]` | | Returns `[ReflectiveInjector](reflectiveinjector)` | | The passed-in providers can be an array of `[Type](type)`, `[Provider](provider)`, or a recursive array of more providers. | | Usage Notes Example ``` class ParentProvider {} class ChildProvider {} var parent = ReflectiveInjector.resolveAndCreate([ParentProvider]); var child = parent.resolveAndCreateChild([ChildProvider]); expect(child.get(ParentProvider) instanceof ParentProvider).toBe(true); expect(child.get(ChildProvider) instanceof ChildProvider).toBe(true); expect(child.get(ParentProvider)).toBe(parent.get(ParentProvider)); ``` | | createChildFromResolved() | | --- | | Creates a child injector from previously resolved providers. | | `abstract createChildFromResolved(providers: ResolvedReflectiveProvider[]): ReflectiveInjector` Parameters | | | | | --- | --- | --- | | `providers` | `[ResolvedReflectiveProvider](resolvedreflectiveprovider)[]` | | Returns `[ReflectiveInjector](reflectiveinjector)` | | This API is the recommended way to construct injectors in performance-sensitive parts. | | Usage Notes Example ``` class ParentProvider {} class ChildProvider {} var parentProviders = ReflectiveInjector.resolve([ParentProvider]); var childProviders = ReflectiveInjector.resolve([ChildProvider]); var parent = ReflectiveInjector.fromResolvedProviders(parentProviders); var child = parent.createChildFromResolved(childProviders); expect(child.get(ParentProvider) instanceof ParentProvider).toBe(true); expect(child.get(ChildProvider) instanceof ChildProvider).toBe(true); expect(child.get(ParentProvider)).toBe(parent.get(ParentProvider)); ``` | | resolveAndInstantiate() | | --- | | Resolves a provider and instantiates an object in the context of the injector. | | `abstract resolveAndInstantiate(provider: Provider): any` Parameters | | | | | --- | --- | --- | | `provider` | `[Provider](provider)` | | Returns `any` | | The created object does not get cached by the injector. | | Usage Notes Example ``` @Injectable() class Engine { } @Injectable() class Car { constructor(public engine:Engine) {} } var injector = ReflectiveInjector.resolveAndCreate([Engine]); var car = injector.resolveAndInstantiate(Car); expect(car.engine).toBe(injector.get(Engine)); expect(car).not.toBe(injector.resolveAndInstantiate(Car)); ``` | | instantiateResolved() | | --- | | Instantiates an object using a resolved provider in the context of the injector. | | `abstract instantiateResolved(provider: ResolvedReflectiveProvider): any` Parameters | | | | | --- | --- | --- | | `provider` | `[ResolvedReflectiveProvider](resolvedreflectiveprovider)` | | Returns `any` | | The created object does not get cached by the injector. | | Usage Notes Example ``` @Injectable() class Engine { } @Injectable() class Car { constructor(public engine:Engine) {} } var injector = ReflectiveInjector.resolveAndCreate([Engine]); var carProvider = ReflectiveInjector.resolve([Car])[0]; var car = injector.instantiateResolved(carProvider); expect(car.engine).toBe(injector.get(Engine)); expect(car).not.toBe(injector.instantiateResolved(carProvider)); ``` | | get() | | --- | | `abstract get(token: any, notFoundValue?: any): any` Parameters | | | | | --- | --- | --- | | `token` | `any` | | | `notFoundValue` | `any` | Optional. Default is `undefined`. | Returns `any` | Usage notes ----------- ### Example The following example creates an `[Injector](injector)` configured to create `Engine` and `Car`. ``` @Injectable() class Engine { } @Injectable() class Car { constructor(public engine:Engine) {} } var injector = ReflectiveInjector.resolveAndCreate([Car, Engine]); var car = injector.get(Car); expect(car instanceof Car).toBe(true); expect(car.engine instanceof Engine).toBe(true); ``` Notice, we don't use the `new` operator because we explicitly want to have the `[Injector](injector)` resolve all of the object's dependencies automatically. TODO: delete in v14.
programming_docs
angular <ng-template> <ng-template> ============= `element` Angular's `[<ng-template>](ng-template)` element defines a template that is not rendered by default. [See more...](ng-template#description) Description ----------- With `[<ng-template>](ng-template)`, you can define template content that is only being rendered by Angular when you, whether directly or indirectly, specifically instruct it to do so, allowing you to have full control over how and when the content is displayed. Note that if you wrap content inside an `[<ng-template>](ng-template)` without instructing Angular to render it, such content will not appear on a page. For example, see the following HTML code, when handling it Angular won't render the middle "Hip!" in the phrase "Hip! Hip! Hooray!" because of the surrounding `[<ng-template>](ng-template)`. ``` <p>Hip!</p> <ng-template> <p>Hip!</p> </ng-template> <p>Hooray!</p> ``` Further information is available in the [Usage Notes...](ng-template#usage-notes) Usage notes ----------- ### Structural Directives One of the main uses for `[<ng-template>](ng-template)` is to hold template content that will be used by [Structural directives](../../guide/structural-directives). Those directives can add and remove copies of the template content based on their own logic. When using the [structural directive shorthand](../../guide/structural-directives#structural-directive-shorthand), Angular creates an `[<ng-template>](ng-template)` element behind the scenes. ### TemplateRef `[<ng-template>](ng-template)` elements are represented as instances of the `[TemplateRef](templateref)` class. To add copies of the template to the DOM, pass this object to the `[ViewContainerRef](viewcontainerref)` method `createEmbeddedView()`. ### Template Variables `[<ng-template>](ng-template)` elements can be referenced in templates using [standard template variables](../../guide/template-reference-variables#how-angular-assigns-values-to-template-variables). *This is how `[<ng-template>](ng-template)` elements are used as `[ngIf](../common/ngif)` else clauses.* Such template variables can be used in conjunction with `[ngTemplateOutlet](../common/ngtemplateoutlet)` directives to render the content defined inside `[<ng-template>](ng-template)` tags. ### Querying A [Query](query) (such as `[ViewChild](viewchild)`) can find the `[TemplateRef](templateref)` associated to an `[<ng-template>](ng-template)` element so that it can be used programmatically; for instance, to pass it to the `[ViewContainerRef](viewcontainerref)` method `createEmbeddedView()`. ### Context Inside the `[<ng-template>](ng-template)` tags you can reference variables present in the surrounding outer template. Additionally, a context object can be associated with `[<ng-template>](ng-template)` elements. Such an object contains variables that can be accessed from within the template contents via template (`let` and `as`) declarations. angular Self Self ==== `decorator` Parameter decorator to be used on constructor parameters, which tells the DI framework to start dependency resolution from the local injector. [See more...](self#description) See also -------- * `[SkipSelf](skipself)` * `[Optional](optional)` Description ----------- Resolution works upward through the injector hierarchy, so the children of this class must configure their own providers or be prepared for a `null` result. Further information is available in the [Usage Notes...](self#usage-notes) Options ------- Usage notes ----------- In the following example, the dependency can be resolved by the local injector when instantiating the class itself, but not when instantiating a child. ``` class Dependency {} @Injectable() class NeedsDependency { constructor(@Self() public dependency: Dependency) {} } let inj = Injector.create({ providers: [ {provide: Dependency, deps: []}, {provide: NeedsDependency, deps: [[new Self(), Dependency]]} ] }); const nd = inj.get(NeedsDependency); expect(nd.dependency instanceof Dependency).toBe(true); const child = Injector.create({ providers: [{provide: NeedsDependency, deps: [[new Self(), Dependency]]}], parent: inj }); expect(() => child.get(NeedsDependency)).toThrowError(); ``` angular ChangeDetectorRef ChangeDetectorRef ================= `class` Base class that provides change detection functionality. A change-detection tree collects all views that are to be checked for changes. Use the methods to add and remove views from the tree, initiate change-detection, and explicitly mark views as *dirty*, meaning that they have changed and need to be re-rendered. ``` abstract class ChangeDetectorRef { abstract markForCheck(): void abstract detach(): void abstract detectChanges(): void abstract checkNoChanges(): void abstract reattach(): void } ``` Subclasses ---------- * `[ViewRef](viewref)` + `[EmbeddedViewRef](embeddedviewref)` See also -------- * [Using change detection hooks](../../guide/lifecycle-hooks#using-change-detection-hooks) * [Defining custom change detection](../../guide/lifecycle-hooks#defining-custom-change-detection) Methods ------- | markForCheck() | | --- | | When a view uses the [OnPush](changedetectionstrategy#OnPush) (checkOnce) change detection strategy, explicitly marks the view as changed so that it can be checked again. | | `abstract markForCheck(): void` Parameters There are no parameters. Returns `void` | | Components are normally marked as dirty (in need of rerendering) when inputs have changed or events have fired in the view. Call this method to ensure that a component is checked even if these triggers have not occurred. | | detach() | | --- | | Detaches this view from the change-detection tree. A detached view is not checked until it is reattached. Use in combination with `detectChanges()` to implement local change detection checks. | | `abstract detach(): void` Parameters There are no parameters. Returns `void` | | Detached views are not checked during change detection runs until they are re-attached, even if they are marked as dirty. | | detectChanges() | | --- | | Checks this view and its children. Use in combination with [detach](changedetectorref#detach) to implement local change detection checks. | | `abstract detectChanges(): void` Parameters There are no parameters. Returns `void` | | | | checkNoChanges() | | --- | | Checks the change detector and its children, and throws if any changes are detected. | | `abstract checkNoChanges(): void` Parameters There are no parameters. Returns `void` | | Use in development mode to verify that running change detection doesn't introduce other changes. Calling it in production mode is a noop. | | reattach() | | --- | | Re-attaches the previously detached view to the change detection tree. Views are attached to the tree by default. | | `abstract reattach(): void` Parameters There are no parameters. Returns `void` | | | Usage notes ----------- The following examples demonstrate how to modify default change-detection behavior to perform explicit detection when needed. ### Use `markForCheck()` with `CheckOnce` strategy The following example sets the `OnPush` change-detection strategy for a component (`CheckOnce`, rather than the default `CheckAlways`), then forces a second check after an interval. See [live demo](https://plnkr.co/edit/GC512b?p=preview). ``` @Component({ selector: 'app-root', template: `Number of ticks: {{numberOfTicks}}`, changeDetection: ChangeDetectionStrategy.OnPush, }) class AppComponent { numberOfTicks = 0; constructor(private ref: ChangeDetectorRef) { setInterval(() => { this.numberOfTicks++; // require view to be updated this.ref.markForCheck(); }, 1000); } } ``` ### Detach change detector to limit how often check occurs The following example defines a component with a large list of read-only data that is expected to change constantly, many times per second. To improve performance, we want to check and update the list less often than the changes actually occur. To do that, we detach the component's change detector and perform an explicit local check every five seconds. ``` class DataListProvider { // in a real application the returned data will be different every time get data() { return [1, 2, 3, 4, 5]; } } @Component({ selector: 'giant-list', template: ` <li *ngFor="let d of dataProvider.data">Data {{d}}</li> `, }) class GiantList { constructor(private ref: ChangeDetectorRef, public dataProvider: DataListProvider) { ref.detach(); setInterval(() => { this.ref.detectChanges(); }, 5000); } } @Component({ selector: 'app', providers: [DataListProvider], template: ` <giant-list></giant-list> `, }) class App { } ``` ### Reattaching a detached component The following example creates a component displaying live data. The component detaches its change detector from the main change detector tree when the `live` property is set to false, and reattaches it when the property becomes true. ``` class DataProvider { data = 1; constructor() { setInterval(() => { this.data = 2; }, 500); } } @Component({selector: 'live-data', inputs: ['live'], template: 'Data: {{dataProvider.data}}'}) class LiveData { constructor(private ref: ChangeDetectorRef, public dataProvider: DataProvider) {} @Input() set live(value: boolean) { if (value) { this.ref.reattach(); } else { this.ref.detach(); } } } @Component({ selector: 'app', providers: [DataProvider], template: ` Live Update: <input type="checkbox" [(ngModel)]="live"> <live-data [live]="live"></live-data> `, }) class App1 { live = true; } ``` angular QueryList QueryList ========= `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An unmodifiable list of items that Angular keeps up to date when the state of the application changes. [See more...](querylist#description) ``` class QueryList<T> implements Iterable<T> { constructor(_emitDistinctChangesOnly: boolean = false) dirty: true length: number first: T last: T changes: Observable<any> get(index: number): T | undefined map<U>(fn: (item: T, index: number, array: T[]) => U): U[] filter(fn: (item: T, index: number, array: T[]) => boolean): T[] find(fn: (item: T, index: number, array: T[]) => boolean): T | undefined reduce<U>(fn: (prevValue: U, curValue: T, curIndex: number, array: T[]) => U, init: U): U forEach(fn: (item: T, index: number, array: T[]) => void): void some(fn: (value: T, index: number, array: T[]) => boolean): boolean toArray(): T[] toString(): string reset(resultsTree: (any[] | T)[], identityAccessor?: (value: T) => unknown): void notifyOnChanges(): void setDirty() destroy(): void } ``` Description ----------- The type of object that [`ViewChildren`](viewchildren), [`ContentChildren`](contentchildren), and [`QueryList`](querylist) provide. Implements an iterable interface, therefore it can be used in both ES6 javascript `for (var i of items)` loops as well as in Angular templates with `*[ngFor](../common/ngfor)="let i of myList"`. Changes can be observed by subscribing to the changes `Observable`. NOTE: In the future this class will implement an `Observable` interface. Further information is available in the [Usage Notes...](querylist#usage-notes) Constructor ----------- | | | | | | --- | --- | --- | --- | | `constructor(_emitDistinctChangesOnly: boolean = false)` Parameters | | | | | --- | --- | --- | | `_emitDistinctChangesOnly` | `boolean` | Optional. Default is `false`. | | Properties ---------- | Property | Description | | --- | --- | | `dirty: true` | Read-Only | | `length: number` | Read-Only | | `first: T` | Read-Only | | `last: T` | Read-Only | | `changes: Observable<any>` | Read-Only Returns `Observable` of `[QueryList](querylist)` notifying the subscriber of changes. | Methods ------- | get() | | --- | | Returns the QueryList entry at `index`. | | `get(index: number): T | undefined` Parameters | | | | | --- | --- | --- | | `index` | `number` | | Returns `T | undefined` | | map() | | --- | | See [Array.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) | | `map<U>(fn: (item: T, index: number, array: T[]) => U): U[]` Parameters | | | | | --- | --- | --- | | `fn` | `(item: T, index: number, array: T[]) => U` | | Returns `U[]` | | filter() | | --- | | See [Array.filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) | | `filter(fn: (item: T, index: number, array: T[]) => boolean): T[]` Parameters | | | | | --- | --- | --- | | `fn` | `(item: T, index: number, array: T[]) => boolean` | | Returns `T[]` | | find() | | --- | | See [Array.find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) | | `find(fn: (item: T, index: number, array: T[]) => boolean): T | undefined` Parameters | | | | | --- | --- | --- | | `fn` | `(item: T, index: number, array: T[]) => boolean` | | Returns `T | undefined` | | reduce() | | --- | | See [Array.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) | | `reduce<U>(fn: (prevValue: U, curValue: T, curIndex: number, array: T[]) => U, init: U): U` Parameters | | | | | --- | --- | --- | | `fn` | `(prevValue: U, curValue: T, curIndex: number, array: T[]) => U` | | | `init` | `U` | | Returns `U` | | forEach() | | --- | | See [Array.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) | | `forEach(fn: (item: T, index: number, array: T[]) => void): void` Parameters | | | | | --- | --- | --- | | `fn` | `(item: T, index: number, array: T[]) => void` | | Returns `void` | | some() | | --- | | See [Array.some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) | | `some(fn: (value: T, index: number, array: T[]) => boolean): boolean` Parameters | | | | | --- | --- | --- | | `fn` | `(value: T, index: number, array: T[]) => boolean` | | Returns `boolean` | | toArray() | | --- | | Returns a copy of the internal results list as an Array. | | `toArray(): T[]` Parameters There are no parameters. Returns `T[]` | | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | | reset() | | --- | | Updates the stored data of the query list, and resets the `dirty` flag to `false`, so that on change detection, it will not notify of changes to the queries, unless a new change occurs. | | `reset(resultsTree: (any[] | T)[], identityAccessor?: (value: T) => unknown): void` Parameters | | | | | --- | --- | --- | | `resultsTree` | `(any[] | T)[]` | The query results to store | | `identityAccessor` | `(value: T) => unknown` | Optional function for extracting stable object identity from a value in the array. This function is executed for each element of the query result list while comparing current query list with the new one (provided as a first argument of the `reset` function) to detect if the lists are different. If the function is not provided, elements are compared as is (without any pre-processing). Optional. Default is `undefined`. | Returns `void` | | notifyOnChanges() | | --- | | Triggers a change event by emitting on the `changes` [`EventEmitter`](eventemitter). | | `notifyOnChanges(): void` Parameters There are no parameters. Returns `void` | | setDirty() | | --- | | internal | | `setDirty()` Parameters There are no parameters. | | destroy() | | --- | | internal | | `destroy(): void` Parameters There are no parameters. Returns `void` | Usage notes ----------- ### Example ``` @Component({...}) class Container { @ViewChildren(Item) items:QueryList<Item>; } ``` angular FactorySansProvider FactorySansProvider =================== `interface` Configures the `[Injector](injector)` to return a value by invoking a `useFactory` function. ``` interface FactorySansProvider { useFactory: Function deps?: any[] } ``` Child interfaces ---------------- * `[FactoryProvider](factoryprovider)` See also -------- * `[FactoryProvider](factoryprovider)` * ["Dependency Injection Guide"](../../guide/dependency-injection). Properties ---------- | Property | Description | | --- | --- | | `useFactory: Function` | A function to invoke to create a value for this `token`. The function is invoked with resolved values of `token`s in the `deps` field. | | `deps?: any[]` | A list of `token`s to be resolved by the injector. The list of values is then used as arguments to the `useFactory` function. | angular KeyValueChangeRecord KeyValueChangeRecord ==================== `interface` Record representing the item change information. ``` interface KeyValueChangeRecord<K, V> { key: K currentValue: V | null previousValue: V | null } ``` Properties ---------- | Property | Description | | --- | --- | | `key: K` | Read-Only Current key in the Map. | | `currentValue: V | null` | Read-Only Current value for the key or `null` if removed. | | `previousValue: V | null` | Read-Only Previous value for the key or `null` if added. | angular ReflectiveKey ReflectiveKey ============= `class` `deprecated` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A unique object used for retrieving items from the [`ReflectiveInjector`](reflectiveinjector). [See more...](reflectivekey#description) **Deprecated:** No replacement ``` class ReflectiveKey { static numberOfKeys: number static get(token: Object): ReflectiveKey constructor(token: Object, id: number) displayName: string token: Object id: number } ``` Description ----------- Keys have: * a system-wide unique `id`. * a `token`. `Key` is used internally by [`ReflectiveInjector`](reflectiveinjector) because its system-wide unique `id` allows the injector to store created objects in a more efficient way. `Key` should not be created directly. [`ReflectiveInjector`](reflectiveinjector) creates keys automatically when resolving providers. Static properties ----------------- | Property | Description | | --- | --- | | `[static](../upgrade/static) numberOfKeys: number` | Read-Only | Static methods -------------- | get() | | --- | | Retrieves a `Key` for a token. | | `static get(token: Object): ReflectiveKey` Parameters | | | | | --- | --- | --- | | `token` | `Object` | | Returns `[ReflectiveKey](reflectivekey)` | Constructor ----------- | | | --- | | Private This class is "final" and should not be extended. See the [public API notes](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes). | | `constructor(token: Object, id: number)` Parameters | | | | | --- | --- | --- | | `token` | `Object` | | | `id` | `number` | | | Properties ---------- | Property | Description | | --- | --- | | `displayName: string` | Read-Only | | `token: Object` | Declared in Constructor | | `id: number` | Declared in Constructor | angular ClassProvider ClassProvider ============= `interface` Configures the `[Injector](injector)` to return an instance of `useClass` for a token. ``` interface ClassProvider extends ClassSansProvider { provide: any multi?: boolean // inherited from core/ClassSansProvider useClass: Type<any> } ``` See also -------- * ["Dependency Injection Guide"](../../guide/dependency-injection). Properties ---------- | Property | Description | | --- | --- | | `provide: any` | An injection token. (Typically an instance of `[Type](type)` or `[InjectionToken](injectiontoken)`, but can be `any`). | | `multi?: boolean` | When true, injector returns an array of instances. This is useful to allow multiple providers spread across many files to provide configuration information to a common token. | Usage notes ----------- ``` abstract class Shape { name!: string; } class Square extends Shape { override name = 'square'; } const injector = ReflectiveInjector.resolveAndCreate([{provide: Shape, useClass: Square}]); const shape: Shape = injector.get(Shape); expect(shape.name).toEqual('square'); expect(shape instanceof Square).toBe(true); ``` Note that following two providers are not equal: ``` class Greeting { salutation = 'Hello'; } class FormalGreeting extends Greeting { override salutation = 'Greetings'; } const injector = ReflectiveInjector.resolveAndCreate( [FormalGreeting, {provide: Greeting, useClass: FormalGreeting}]); // The injector returns different instances. // See: {provide: ?, useExisting: ?} if you want the same instance. expect(injector.get(FormalGreeting)).not.toBe(injector.get(Greeting)); ``` ### Multi-value example ``` const locale = new InjectionToken<string[]>('locale'); const injector = Injector.create({ providers: [ {provide: locale, multi: true, useValue: 'en'}, {provide: locale, multi: true, useValue: 'sk'}, ] }); const locales: string[] = injector.get(locale); expect(locales).toEqual(['en', 'sk']); ```
programming_docs
angular StaticClassSansProvider StaticClassSansProvider ======================= `interface` Configures the `[Injector](injector)` to return an instance of `useClass` for a token. Base for `[StaticClassProvider](staticclassprovider)` decorator. ``` interface StaticClassSansProvider { useClass: Type<any> deps: any[] } ``` Child interfaces ---------------- * `[StaticClassProvider](staticclassprovider)` Properties ---------- | Property | Description | | --- | --- | | `useClass: [Type](type)<any>` | An optional class to instantiate for the `token`. By default, the `provide` class is instantiated. | | `deps: any[]` | A list of `token`s to be resolved by the injector. The list of values is then used as arguments to the `useClass` constructor. | angular ComponentRef ComponentRef ============ `class` Represents a component created by a `[ComponentFactory](componentfactory)`. Provides access to the component instance and related objects, and provides the means of destroying the instance. ``` abstract class ComponentRef<C> { abstract location: ElementRef abstract injector: Injector abstract instance: C abstract hostView: ViewRef abstract changeDetectorRef: ChangeDetectorRef abstract componentType: Type<any> abstract setInput(name: string, value: unknown): void abstract destroy(): void abstract onDestroy(callback: Function): void } ``` Properties ---------- | Property | Description | | --- | --- | | `abstract location: [ElementRef](elementref)` | Read-Only The host or anchor [element](../../guide/glossary#element) for this component instance. | | `abstract injector: [Injector](injector)` | Read-Only The [dependency injector](../../guide/glossary#injector) for this component instance. | | `abstract instance: C` | Read-Only This component instance. | | `abstract hostView: [ViewRef](viewref)` | Read-Only The [host view](../../guide/glossary#view-tree) defined by the template for this component instance. | | `abstract changeDetectorRef: [ChangeDetectorRef](changedetectorref)` | Read-Only The change detector for this component instance. | | `abstract componentType: [Type](type)<any>` | Read-Only The type of this component (as created by a `[ComponentFactory](componentfactory)` class). | Methods ------- | setInput() | | --- | | Updates a specified input name to a new value. Using this method will properly mark for check component using the `OnPush` change detection strategy. It will also assure that the `[OnChanges](onchanges)` lifecycle hook runs when a dynamically created component is change-detected. | | `abstract setInput(name: string, value: unknown): void` Parameters | | | | | --- | --- | --- | | `name` | `string` | The name of an input. | | `value` | `unknown` | The new value of an input. | Returns `void` | | destroy() | | --- | | Destroys the component instance and all of the data structures associated with it. | | `abstract destroy(): void` Parameters There are no parameters. Returns `void` | | onDestroy() | | --- | | A lifecycle hook that provides additional developer-defined cleanup functionality for the component. | | `abstract onDestroy(callback: Function): void` Parameters | | | | | --- | --- | --- | | `callback` | `Function` | A handler function that cleans up developer-defined data associated with this component. Called when the `destroy()` method is invoked. | Returns `void` | angular INJECTOR INJECTOR ======== `const` An InjectionToken that gets the current `[Injector](injector)` for `createInjector()`-style injectors. [See more...](injector#description) ### `const INJECTOR: InjectionToken<Injector>;` #### Description Requesting this token instead of `[Injector](injector)` allows `StaticInjector` to be tree-shaken from a project. angular importProvidersFrom importProvidersFrom =================== `function` Collects providers from all NgModules and standalone components, including transitively imported ones. [See more...](importprovidersfrom#description) ### `importProvidersFrom(...sources: ImportProvidersSource[]): EnvironmentProviders` ###### Parameters | | | | | --- | --- | --- | | `sources` | `[ImportProvidersSource](importproviderssource)[]` | | ###### Returns `[EnvironmentProviders](environmentproviders)`: Collected providers from the specified list of types. Description ----------- Providers extracted via `[importProvidersFrom](importprovidersfrom)` are only usable in an application injector or another environment injector (such as a route injector). They should not be used in component providers. More information about standalone components can be found in [this guide](../../guide/standalone-components). Further information is available in the [Usage Notes...](importprovidersfrom#usage-notes) Usage notes ----------- The results of the `[importProvidersFrom](importprovidersfrom)` call can be used in the `[bootstrapApplication](../platform-browser/bootstrapapplication)` call: ``` await bootstrapApplication(RootComponent, { providers: [ importProvidersFrom(NgModuleOne, NgModuleTwo) ] }); ``` You can also use the `[importProvidersFrom](importprovidersfrom)` results in the `providers` field of a route, when a standalone component is used: ``` export const ROUTES: Route[] = [ { path: 'foo', providers: [ importProvidersFrom(NgModuleOne, NgModuleTwo) ], component: YourStandaloneComponent } ]; ``` angular APP_ID APP\_ID ======= `const` A [DI token](../../guide/glossary#di-token "DI token definition") representing a unique string ID, used primarily for prefixing application attributes and CSS styles when [ViewEncapsulation.Emulated](viewencapsulation#Emulated) is being used. [See more...](app_id#description) ### `const APP_ID: InjectionToken<string>;` #### Description BY default, the value is randomly generated and assigned to the application by Angular. To provide a custom ID value, use a DI provider to configure the root [`Injector`](injector) that uses this token. angular getNgModuleById getNgModuleById =============== `function` Returns the NgModule class with the given id (specified using [@NgModule.id field](ngmodule#id)), if it exists and has been loaded. Classes for NgModules that do not specify an `id` cannot be retrieved. Throws if an NgModule cannot be found. ### `getNgModuleById<T>(id: string): Type<T>` ###### Parameters | | | | | --- | --- | --- | | `id` | `string` | | ###### Returns `[Type<T>](type)` angular OnChanges OnChanges ========= `interface` A lifecycle hook that is called when any data-bound property of a directive changes. Define an `ngOnChanges()` method to handle the changes. ``` interface OnChanges { ngOnChanges(changes: SimpleChanges): void } ``` Class implementations --------------------- * `[NgTemplateOutlet](../common/ngtemplateoutlet)` * `[NgComponentOutlet](../common/ngcomponentoutlet)` * `[NgOptimizedImage](../common/ngoptimizedimage)` * `[NgModel](../forms/ngmodel)` * `[FormControlDirective](../forms/formcontroldirective)` * `[FormControlName](../forms/formcontrolname)` * `[FormGroupDirective](../forms/formgroupdirective)` * `[RouterLink](../router/routerlink)` * `[RouterLinkWithHref](../router/routerlinkwithhref)` * `[RouterLinkActive](../router/routerlinkactive)` * `[UpgradeComponent](../upgrade/static/upgradecomponent)` See also -------- * `[DoCheck](docheck)` * `[OnInit](oninit)` * [Lifecycle hooks guide](../../guide/lifecycle-hooks) Methods ------- | ngOnChanges() | | --- | | A callback method that is invoked immediately after the default change detector has checked data-bound properties if at least one has changed, and before the view and content children are checked. | | `ngOnChanges(changes: SimpleChanges): void` Parameters | | | | | --- | --- | --- | | `changes` | `[SimpleChanges](simplechanges)` | The changed properties. | Returns `void` | Usage notes ----------- The following snippet shows how a component can implement this interface to define an on-changes handler for an input property. ``` @Component({selector: 'my-cmp', template: `...`}) class MyComponent implements OnChanges { @Input() prop: number = 0; ngOnChanges(changes: SimpleChanges) { // changes.prop contains the old and the new value... } } ``` angular EnvironmentProviders EnvironmentProviders ==================== `type-alias` Encapsulated `[Provider](provider)`s that are only accepted during creation of an `[EnvironmentInjector](environmentinjector)` (e.g. in an `[NgModule](ngmodule)`). [See more...](environmentproviders#description) ``` type EnvironmentProviders = { ɵbrand: 'EnvironmentProviders'; }; ``` See also -------- * `[makeEnvironmentProviders](makeenvironmentproviders)` * `[importProvidersFrom](importprovidersfrom)` Description ----------- Using this wrapper type prevents providers which are only designed to work in application/environment injectors from being accidentally included in `@Component.providers` and ending up in a component injector. This wrapper type prevents access to the `[Provider](provider)`s inside. angular ViewChild ViewChild ========= `decorator` Property decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM. If the view DOM changes, and a new child matches the selector, the property is updated. [See more...](viewchild#description) Description ----------- View queries are set before the `ngAfterViewInit` callback is called. **Metadata Properties**: * **selector** - The directive type or the name used for querying. * **read** - Used to read a different token from the queried elements. * **static** - True to resolve query results before change detection runs, false to resolve after change detection. Defaults to false. The following selectors are supported. * Any class with the `@[Component](component)` or `@[Directive](directive)` decorator * A template reference variable as a string (e.g. query `<my-component #cmp></my-component>` with `@[ViewChild](viewchild)('cmp')`) * Any provider defined in the child component tree of the current component (e.g. `@[ViewChild](viewchild)(SomeService) someService: SomeService`) * Any provider defined through a string token (e.g. `@[ViewChild](viewchild)('someToken') someTokenVal: any`) * A `[TemplateRef](templateref)` (e.g. query `<ng-template></ng-template>` with `@[ViewChild](viewchild)([TemplateRef](templateref)) template;`) The following values are supported by `read`: * Any class with the `@[Component](component)` or `@[Directive](directive)` decorator * Any provider defined on the injector of the component that is matched by the `selector` of this query * Any provider defined through a string token (e.g. `{provide: 'token', useValue: 'val'}`) * `[TemplateRef](templateref)`, `[ElementRef](elementref)`, and `[ViewContainerRef](viewcontainerref)` Further information is available in the [Usage Notes...](viewchild#usage-notes) Options ------- Usage notes ----------- ``` import {Component, Directive, Input, ViewChild} from '@angular/core'; @Directive({selector: 'pane'}) export class Pane { @Input() id!: string; } @Component({ selector: 'example-app', template: ` <pane id="1" *ngIf="shouldShow"></pane> <pane id="2" *ngIf="!shouldShow"></pane> <button (click)="toggle()">Toggle</button> <div>Selected: {{selectedPane}}</div> `, }) export class ViewChildComp { @ViewChild(Pane) set pane(v: Pane) { setTimeout(() => { this.selectedPane = v.id; }, 0); } selectedPane: string = ''; shouldShow = true; toggle() { this.shouldShow = !this.shouldShow; } } ``` ### Example 2 ``` import {AfterViewInit, Component, Directive, ViewChild} from '@angular/core'; @Directive({selector: 'child-directive'}) class ChildDirective { } @Component({selector: 'someCmp', templateUrl: 'someCmp.html'}) class SomeCmp implements AfterViewInit { @ViewChild(ChildDirective) child!: ChildDirective; ngAfterViewInit() { // child is set } } ``` angular Component Component ========= `decorator` Decorator that marks a class as an Angular component and provides configuration metadata that determines how the component should be processed, instantiated, and used at runtime. [See more...](component#description) | Option | Description | | --- | --- | | [`changeDetection?`](component#changeDetection) | The change-detection strategy to use for this component. | | [`viewProviders?`](component#viewProviders) | Defines the set of injectable objects that are visible to its view DOM children. See [example](component#injecting-a-class-with-a-view-provider). | | [`moduleId?`](component#moduleId) | The module ID of the module that contains the component. The component must be able to resolve relative URLs for templates and styles. SystemJS exposes the `__moduleName` variable within each module. In CommonJS, this can be set to `module.id`. | | [`templateUrl?`](component#templateUrl) | The relative path or absolute URL of a template file for an Angular component. If provided, do not supply an inline template using `template`. | | [`template?`](component#template) | An inline template for an Angular component. If provided, do not supply a template file using `templateUrl`. | | [`styleUrls?`](component#styleUrls) | One or more relative paths or absolute URLs for files containing CSS stylesheets to use in this component. | | [`styles?`](component#styles) | One or more inline CSS stylesheets to use in this component. | | [`animations?`](component#animations) | One or more animation `[trigger](../animations/trigger)()` calls, containing [`state()`](../animations/state) and `[transition](../animations/transition)()` definitions. See the [Animations guide](../../guide/animations) and animations API documentation. | | [`encapsulation?`](component#encapsulation) | An encapsulation policy for the component's styling. Possible values:* `[ViewEncapsulation.Emulated](viewencapsulation#Emulated)`: Apply modified component styles in order to emulate a native Shadow DOM CSS encapsulation behavior. * `[ViewEncapsulation.None](viewencapsulation#None)`: Apply component styles globally without any sort of encapsulation. * `[ViewEncapsulation.ShadowDom](viewencapsulation#ShadowDom)`: Use the browser's native Shadow DOM API to encapsulate styles. | | [`interpolation?`](component#interpolation) | Overrides the default interpolation start and end delimiters (`{{` and `}}`). | | [`entryComponents?`](component#entryComponents) | A set of components that should be compiled along with this component. For each component listed here, Angular creates a [`ComponentFactory`](componentfactory) and stores it in the [`ComponentFactoryResolver`](componentfactoryresolver). | | [`preserveWhitespaces?`](component#preserveWhitespaces) | True to preserve or false to remove potentially superfluous whitespace characters from the compiled template. Whitespace characters are those matching the `\s` character class in JavaScript regular expressions. Default is false, unless overridden in compiler options. | | [`standalone?`](component#standalone) | Angular components marked as `standalone` do not need to be declared in an NgModule. Such components directly manage their own template dependencies (components, directives, and pipes used in a template) via the imports property. | | [`imports?`](component#imports) | The imports property specifies the standalone component's template dependencies — those directives, components, and pipes that can be used within its template. Standalone components can import other standalone components, directives, and pipes as well as existing NgModules. | | [`schemas?`](component#schemas) | The set of schemas that declare elements to be allowed in a standalone component. Elements and properties that are neither Angular components nor directives must be declared in a schema. | ### Inherited from [Directive](directive) decorator | Option | Description | | --- | --- | | [`selector?`](directive#selector) | The CSS selector that identifies this directive in a template and triggers instantiation of the directive. | | [`inputs?`](directive#inputs) | Enumerates the set of data-bound input properties for a directive | | [`outputs?`](directive#outputs) | Enumerates the set of event-bound output properties. | | [`providers?`](directive#providers) | Configures the [injector](../../guide/glossary#injector) of this directive or component with a [token](../../guide/glossary#di-token) that maps to a [provider](../../guide/glossary#provider) of a dependency. | | [`exportAs?`](directive#exportAs) | Defines the name that can be used in the template to assign this directive to a variable. | | [`queries?`](directive#queries) | Configures the queries that will be injected into the directive. | | [`host?`](directive#host) | Maps class properties to host element bindings for properties, attributes, and events, using a set of key-value pairs. | | [`jit?`](directive#jit) | When present, this directive/component is ignored by the AOT compiler. It remains in distributed code, and the JIT compiler attempts to compile it at run time, in the browser. To ensure the correct behavior, the app must import `@angular/compiler`. | | [`standalone?`](directive#standalone) | Angular directives marked as `standalone` do not need to be declared in an NgModule. Such directives don't depend on any "intermediate context" of an NgModule (ex. configured providers). | | [`hostDirectives?`](directive#hostDirectives) | Standalone directives that should be applied to the host whenever the directive is matched. By default, none of the inputs or outputs of the host directives will be available on the host, unless they are specified in the `inputs` or `outputs` properties. | Description ----------- Components are the most basic UI building block of an Angular app. An Angular app contains a tree of Angular components. Angular components are a subset of directives, always associated with a template. Unlike other directives, only one component can be instantiated for a given element in a template. A component must belong to an NgModule in order for it to be available to another component or application. To make it a member of an NgModule, list it in the `declarations` field of the `[NgModule](ngmodule)` metadata. Note that, in addition to these options for configuring a directive, you can control a component's runtime behavior by implementing life-cycle hooks. For more information, see the [Lifecycle Hooks](../../guide/lifecycle-hooks) guide. Further information is available in the [Usage Notes...](component#usage-notes) Options ------- | changeDetection | | --- | | The change-detection strategy to use for this component. | | `changeDetection?: ChangeDetectionStrategy` | | When a component is instantiated, Angular creates a change detector, which is responsible for propagating the component's bindings. The strategy is one of:* `[ChangeDetectionStrategy](changedetectionstrategy)#OnPush` sets the strategy to `CheckOnce` (on demand). * `[ChangeDetectionStrategy](changedetectionstrategy)#Default` sets the strategy to `CheckAlways`. | | viewProviders | | --- | | Defines the set of injectable objects that are visible to its view DOM children. See [example](component#injecting-a-class-with-a-view-provider). | | `viewProviders?: Provider[]` | | | | moduleId | | --- | | The module ID of the module that contains the component. The component must be able to resolve relative URLs for templates and styles. SystemJS exposes the `__moduleName` variable within each module. In CommonJS, this can be set to `module.id`. | | `moduleId?: string` | | | | templateUrl | | --- | | The relative path or absolute URL of a template file for an Angular component. If provided, do not supply an inline template using `template`. | | `templateUrl?: string` | | | | template | | --- | | An inline template for an Angular component. If provided, do not supply a template file using `templateUrl`. | | `template?: string` | | | | styleUrls | | --- | | One or more relative paths or absolute URLs for files containing CSS stylesheets to use in this component. | | `styleUrls?: string[]` | | | | styles | | --- | | One or more inline CSS stylesheets to use in this component. | | `styles?: string[]` | | | | animations | | --- | | One or more animation `[trigger](../animations/trigger)()` calls, containing [`state()`](../animations/state) and `[transition](../animations/transition)()` definitions. See the [Animations guide](../../guide/animations) and animations API documentation. | | `animations?: any[]` | | | | encapsulation | | --- | | An encapsulation policy for the component's styling. Possible values:* `[ViewEncapsulation.Emulated](viewencapsulation#Emulated)`: Apply modified component styles in order to emulate a native Shadow DOM CSS encapsulation behavior. * `[ViewEncapsulation.None](viewencapsulation#None)`: Apply component styles globally without any sort of encapsulation. * `[ViewEncapsulation.ShadowDom](viewencapsulation#ShadowDom)`: Use the browser's native Shadow DOM API to encapsulate styles. | | `encapsulation?: ViewEncapsulation` | | If not supplied, the value is taken from the `[CompilerOptions](compileroptions)` which defaults to `[ViewEncapsulation.Emulated](viewencapsulation#Emulated)`. If the policy is `[ViewEncapsulation.Emulated](viewencapsulation#Emulated)` and the component has no [styles](component#styles) nor [styleUrls](component#styleUrls), the policy is automatically switched to `[ViewEncapsulation.None](viewencapsulation#None)`. | | interpolation | | --- | | Overrides the default interpolation start and end delimiters (`{{` and `}}`). | | `interpolation?: [ string, string ]` | | | | entryComponents | | --- | | A set of components that should be compiled along with this component. For each component listed here, Angular creates a [`ComponentFactory`](componentfactory) and stores it in the [`ComponentFactoryResolver`](componentfactoryresolver). | | `entryComponents?: Array<Type<any> | any[]>` | | | | preserveWhitespaces | | --- | | True to preserve or false to remove potentially superfluous whitespace characters from the compiled template. Whitespace characters are those matching the `\s` character class in JavaScript regular expressions. Default is false, unless overridden in compiler options. | | `preserveWhitespaces?: boolean` | | | | standalone | | --- | | Angular components marked as `standalone` do not need to be declared in an NgModule. Such components directly manage their own template dependencies (components, directives, and pipes used in a template) via the imports property. | | `standalone?: boolean` | | More information about standalone components, directives, and pipes can be found in [this guide](../../guide/standalone-components). | | imports | | --- | | The imports property specifies the standalone component's template dependencies — those directives, components, and pipes that can be used within its template. Standalone components can import other standalone components, directives, and pipes as well as existing NgModules. | | `imports?: (Type<any> | ReadonlyArray<any>)[]` | | This property is only available for standalone components - specifying it for components declared in an NgModule generates a compilation error. More information about standalone components, directives, and pipes can be found in [this guide](../../guide/standalone-components). | | schemas | | --- | | The set of schemas that declare elements to be allowed in a standalone component. Elements and properties that are neither Angular components nor directives must be declared in a schema. | | `schemas?: SchemaMetadata[]` | | This property is only available for standalone components - specifying it for components declared in an NgModule generates a compilation error. More information about standalone components, directives, and pipes can be found in [this guide](../../guide/standalone-components). | Usage notes ----------- ### Setting component inputs The following example creates a component with two data-bound properties, specified by the `inputs` value. ``` @Component({ selector: 'app-bank-account', inputs: ['bankName', 'id: account-id'], template: ` Bank Name: {{ bankName }} Account Id: {{ id }} ` }) export class BankAccountComponent { bankName: string|null = null; id: string|null = null; // this property is not bound, and won't be automatically updated by Angular normalizedBankName: string|null = null; } @Component({ selector: 'app-my-input', template: ` <app-bank-account bankName="RBC" account-id="4747"> </app-bank-account> ` }) export class MyInputComponent { } ``` ### Setting component outputs The following example shows two event emitters that emit on an interval. One emits an output every second, while the other emits every five seconds. ``` @Directive({selector: 'app-interval-dir', outputs: ['everySecond', 'fiveSecs: everyFiveSeconds']}) export class IntervalDirComponent { everySecond = new EventEmitter<string>(); fiveSecs = new EventEmitter<string>(); constructor() { setInterval(() => this.everySecond.emit('event'), 1000); setInterval(() => this.fiveSecs.emit('event'), 5000); } } @Component({ selector: 'app-my-output', template: ` <app-interval-dir (everySecond)="onEverySecond()" (everyFiveSeconds)="onEveryFiveSeconds()"> </app-interval-dir> ` }) export class MyOutputComponent { onEverySecond() { console.log('second'); } onEveryFiveSeconds() { console.log('five seconds'); } } ``` ### Injecting a class with a view provider The following simple example injects a class into a component using the view provider specified in component metadata: ``` class Greeter { greet(name:string) { return 'Hello ' + name + '!'; } } @Directive({ selector: 'needs-greeter' }) class NeedsGreeter { greeter:Greeter; constructor(greeter:Greeter) { this.greeter = greeter; } } @Component({ selector: 'greet', viewProviders: [ Greeter ], template: `<needs-greeter></needs-greeter>` }) class HelloWorld { } ``` ### Preserving whitespace Removing whitespace can greatly reduce AOT-generated code size and speed up view creation. As of Angular 6, the default for `preserveWhitespaces` is false (whitespace is removed). To change the default setting for all components in your application, set the `preserveWhitespaces` option of the AOT compiler. By default, the AOT compiler removes whitespace characters as follows: * Trims all whitespaces at the beginning and the end of a template. * Removes whitespace-only text nodes. For example, ``` <button>Action 1</button> <button>Action 2</button> ``` becomes: ``` <button>Action 1</button><button>Action 2</button> ``` * Replaces a series of whitespace characters in text nodes with a single space. For example, `<span>\n some text\n</span>` becomes `<span> some text </span>`. * Does NOT alter text nodes inside HTML tags such as `<pre>` or `<[textarea](../forms/defaultvalueaccessor)>`, where whitespace characters are significant. Note that these transformations can influence DOM nodes layout, although impact should be minimal. You can override the default behavior to preserve whitespace characters in certain fragments of a template. For example, you can exclude an entire DOM sub-tree by using the `ngPreserveWhitespaces` attribute: ``` <div ngPreserveWhitespaces> whitespaces are preserved here <span> and here </span> </div> ``` You can force a single space to be preserved in a text node by using `&ngsp;`, which is replaced with a space character by Angular's template compiler: ``` <a>Spaces</a>&ngsp;<a>between</a>&ngsp;<a>links.</a> <!-- compiled to be equivalent to: <a>Spaces</a> <a>between</a> <a>links.</a> --> ``` Note that sequences of `&ngsp;` are still collapsed to just one space character when the `preserveWhitespaces` option is set to `false`. ``` <a>before</a>&ngsp;&ngsp;&ngsp;<a>after</a> <!-- compiled to be equivalent to: <a>before</a> <a>after</a> --> ``` To preserve sequences of whitespace characters, use the `ngPreserveWhitespaces` attribute.
programming_docs
angular IterableDifferFactory IterableDifferFactory ===================== `interface` Provides a factory for [`IterableDiffer`](iterablediffer). ``` interface IterableDifferFactory { supports(objects: any): boolean create<V>(trackByFn?: TrackByFunction<V>): IterableDiffer<V> } ``` Methods ------- | supports() | | --- | | `supports(objects: any): boolean` Parameters | | | | | --- | --- | --- | | `objects` | `any` | | Returns `boolean` | | create() | | --- | | `create<V>(trackByFn?: TrackByFunction<V>): IterableDiffer<V>` Parameters | | | | | --- | --- | --- | | `trackByFn` | `[TrackByFunction](trackbyfunction)<V>` | Optional. Default is `undefined`. | Returns `[IterableDiffer<V>](iterablediffer)` | angular ComponentFactoryResolver ComponentFactoryResolver ======================== `class` `deprecated` A simple registry that maps `Components` to generated `[ComponentFactory](componentfactory)` classes that can be used to create instances of components. Use to obtain the factory for a given component type, then use the factory's `create()` method to create a component of that type. [See more...](componentfactoryresolver#description) **Deprecated:** Angular no longer requires Component factories. Please use other APIs where Component class can be used directly. ``` abstract class ComponentFactoryResolver { static NULL: ComponentFactoryResolver abstract resolveComponentFactory<T>(component: Type<T>): ComponentFactory<T> } ``` Description ----------- Note: since v13, dynamic component creation via [`ViewContainerRef.createComponent`](viewcontainerref#createComponent) does **not** require resolving component factory: component class can be used directly. Static properties ----------------- | Property | Description | | --- | --- | | `[static](../upgrade/static) NULL: [ComponentFactoryResolver](componentfactoryresolver)` | | Methods ------- | resolveComponentFactory() | | --- | | Retrieves the factory object that creates a component of the given type. | | `abstract resolveComponentFactory<T>(component: Type<T>): ComponentFactory<T>` Parameters | | | | | --- | --- | --- | | `component` | `[Type<T>](type)` | The component type. | Returns `[ComponentFactory](componentfactory)<T>` | angular Compiler Compiler ======== `class` `deprecated` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Low-level service for running the angular compiler during runtime to create [`ComponentFactory`](componentfactory)s, which can later be used to create and render a Component instance. [See more...](compiler#description) **Deprecated:** Ivy JIT mode doesn't require accessing this symbol. See [JIT API changes due to ViewEngine deprecation](../../guide/deprecations#jit-api-changes) for additional context. ``` class Compiler { compileModuleSync<T>(moduleType: Type<T>): NgModuleFactory<T> compileModuleAsync<T>(moduleType: Type<T>): Promise<NgModuleFactory<T>> compileModuleAndAllComponentsSync<T>(moduleType: Type<T>): ModuleWithComponentFactories<T> compileModuleAndAllComponentsAsync<T>(moduleType: Type<T>): Promise<ModuleWithComponentFactories<T>> clearCache(): void clearCacheFor(type: Type<any>) getModuleId(moduleType: Type<any>): string | undefined } ``` Provided in ----------- * ``` 'root' ``` Description ----------- Each `@[NgModule](ngmodule)` provides an own `[Compiler](compiler)` to its injector, that will use the directives/pipes of the ng module for compilation of components. Methods ------- | compileModuleSync() | | --- | | Compiles the given NgModule and all of its components. All templates of the components listed in `entryComponents` have to be inlined. | | `compileModuleSync<T>(moduleType: Type<T>): NgModuleFactory<T>` Parameters | | | | | --- | --- | --- | | `moduleType` | `[Type<T>](type)` | | Returns `[NgModuleFactory<T>](ngmodulefactory)` | | compileModuleAsync() | | --- | | Compiles the given NgModule and all of its components | | `compileModuleAsync<T>(moduleType: Type<T>): Promise<NgModuleFactory<T>>` Parameters | | | | | --- | --- | --- | | `moduleType` | `[Type<T>](type)` | | Returns `Promise<[NgModuleFactory](ngmodulefactory)<T>>` | | compileModuleAndAllComponentsSync() | | --- | | Same as [compileModuleSync](compiler#compileModuleSync) but also creates ComponentFactories for all components. | | `compileModuleAndAllComponentsSync<T>(moduleType: Type<T>): ModuleWithComponentFactories<T>` Parameters | | | | | --- | --- | --- | | `moduleType` | `[Type<T>](type)` | | Returns `[ModuleWithComponentFactories<T>](modulewithcomponentfactories)` | | compileModuleAndAllComponentsAsync() | | --- | | Same as [compileModuleAsync](compiler#compileModuleAsync) but also creates ComponentFactories for all components. | | `compileModuleAndAllComponentsAsync<T>(moduleType: Type<T>): Promise<ModuleWithComponentFactories<T>>` Parameters | | | | | --- | --- | --- | | `moduleType` | `[Type<T>](type)` | | Returns `Promise<[ModuleWithComponentFactories](modulewithcomponentfactories)<T>>` | | clearCache() | | --- | | Clears all caches. | | `clearCache(): void` Parameters There are no parameters. Returns `void` | | clearCacheFor() | | --- | | Clears the cache for the given component/ngModule. | | `clearCacheFor(type: Type<any>)` Parameters | | | | | --- | --- | --- | | `type` | `[Type](type)<any>` | | | | getModuleId() | | --- | | Returns the id for a given NgModule, if one is defined and known to the compiler. | | `getModuleId(moduleType: Type<any>): string | undefined` Parameters | | | | | --- | --- | --- | | `moduleType` | `[Type](type)<any>` | | Returns `string | undefined` | angular InjectableType InjectableType ============== `interface` A `[Type](type)` which has a `ɵprov: ɵɵInjectableDeclaration` static field. [See more...](injectabletype#description) ``` interface InjectableType<T> extends Type<T> { // inherited from core/Type constructor(...args: any[]): T } ``` Description ----------- `[InjectableType](injectabletype)`s contain their own Dependency Injection metadata and are usable in an `InjectorDef`-based `StaticInjector`. angular ANALYZE_FOR_ENTRY_COMPONENTS ANALYZE\_FOR\_ENTRY\_COMPONENTS =============================== `const` `deprecated` A DI token that you can use to create a virtual [provider](../../guide/glossary#provider) that will populate the `entryComponents` field of components and NgModules based on its `useValue` property value. All components that are referenced in the `useValue` value (either directly or in a nested array or map) are added to the `entryComponents` property. **Deprecated:** Since 9.0.0. With Ivy, this property is no longer necessary. ### `const ANALYZE_FOR_ENTRY_COMPONENTS: InjectionToken<any>;` #### Usage notes The following example shows how the router can populate the `entryComponents` field of an NgModule based on a router configuration that refers to components. ``` // helper function inside the router function provideRoutes(routes) { return [ {provide: ROUTES, useValue: routes}, {provide: ANALYZE_FOR_ENTRY_COMPONENTS, useValue: routes, multi: true} ]; } // user code let routes = [ {path: '/root', component: RootComp}, {path: '/teams', component: TeamsComp} ]; @NgModule({ providers: [provideRoutes(routes)] }) class ModuleWithRoutes {} ``` angular NgZone NgZone ====== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An injectable service for executing work inside or outside of the Angular zone. [See more...](ngzone#description) ``` class NgZone { static isInAngularZone(): boolean static assertInAngularZone(): void static assertNotInAngularZone(): void constructor(__0) hasPendingMacrotasks: boolean hasPendingMicrotasks: boolean isStable: boolean onUnstable: EventEmitter<any> onMicrotaskEmpty: EventEmitter<any> onStable: EventEmitter<any> onError: EventEmitter<any> run<T>(fn: (...args: any[]) => T, applyThis?: any, applyArgs?: any[]): T runTask<T>(fn: (...args: any[]) => T, applyThis?: any, applyArgs?: any[], name?: string): T runGuarded<T>(fn: (...args: any[]) => T, applyThis?: any, applyArgs?: any[]): T runOutsideAngular<T>(fn: (...args: any[]) => T): T } ``` Provided in ----------- * [``` BrowserTestingModule ```](../platform-browser/testing/browsertestingmodule) Description ----------- The most common use of this service is to optimize performance when starting a work consisting of one or more asynchronous tasks that don't require UI updates or error handling to be handled by Angular. Such tasks can be kicked off via [runOutsideAngular](ngzone#runOutsideAngular) and if needed, these tasks can reenter the Angular zone via [run](ngzone#run). Further information is available in the [Usage Notes...](ngzone#usage-notes) Static methods -------------- | isInAngularZone() | | --- | | `static isInAngularZone(): boolean` Parameters There are no parameters. Returns `boolean` | | assertInAngularZone() | | --- | | `static assertInAngularZone(): void` Parameters There are no parameters. Returns `void` | | assertNotInAngularZone() | | --- | | `static assertNotInAngularZone(): void` Parameters There are no parameters. Returns `void` | Constructor ----------- | | | | | | --- | --- | --- | --- | | `constructor(__0)` Parameters | | | | | --- | --- | --- | | `__0` | | | | Properties ---------- | Property | Description | | --- | --- | | `hasPendingMacrotasks: boolean` | Read-Only | | `hasPendingMicrotasks: boolean` | Read-Only | | `isStable: boolean` | Read-Only Whether there are no outstanding microtasks or macrotasks. | | `onUnstable: [EventEmitter](eventemitter)<any>` | Read-Only Notifies when code enters Angular Zone. This gets fired first on VM Turn. | | `onMicrotaskEmpty: [EventEmitter](eventemitter)<any>` | Read-Only Notifies when there is no more microtasks enqueued in the current VM Turn. This is a hint for Angular to do change detection, which may enqueue more microtasks. For this reason this event can fire multiple times per VM Turn. | | `onStable: [EventEmitter](eventemitter)<any>` | Read-Only Notifies when the last `onMicrotaskEmpty` has run and there are no more microtasks, which implies we are about to relinquish VM turn. This event gets called just once. | | `onError: [EventEmitter](eventemitter)<any>` | Read-Only Notifies that an error has been delivered. | Methods ------- | run() | | --- | | Executes the `fn` function synchronously within the Angular zone and returns value returned by the function. | | `run<T>(fn: (...args: any[]) => T, applyThis?: any, applyArgs?: any[]): T` Parameters | | | | | --- | --- | --- | | `fn` | `(...args: any[]) => T` | | | `applyThis` | `any` | Optional. Default is `undefined`. | | `applyArgs` | `any[]` | Optional. Default is `undefined`. | Returns `T` | | Running functions via `run` allows you to reenter Angular zone from a task that was executed outside of the Angular zone (typically started via [runOutsideAngular](ngzone#runOutsideAngular)). Any future tasks or microtasks scheduled from within this function will continue executing from within the Angular zone. If a synchronous error happens it will be rethrown and not reported via `onError`. | | runTask() | | --- | | Executes the `fn` function synchronously within the Angular zone as a task and returns value returned by the function. | | `runTask<T>(fn: (...args: any[]) => T, applyThis?: any, applyArgs?: any[], name?: string): T` Parameters | | | | | --- | --- | --- | | `fn` | `(...args: any[]) => T` | | | `applyThis` | `any` | Optional. Default is `undefined`. | | `applyArgs` | `any[]` | Optional. Default is `undefined`. | | `name` | `string` | Optional. Default is `undefined`. | Returns `T` | | Running functions via `run` allows you to reenter Angular zone from a task that was executed outside of the Angular zone (typically started via [runOutsideAngular](ngzone#runOutsideAngular)). Any future tasks or microtasks scheduled from within this function will continue executing from within the Angular zone. If a synchronous error happens it will be rethrown and not reported via `onError`. | | runGuarded() | | --- | | Same as `run`, except that synchronous errors are caught and forwarded via `onError` and not rethrown. | | `runGuarded<T>(fn: (...args: any[]) => T, applyThis?: any, applyArgs?: any[]): T` Parameters | | | | | --- | --- | --- | | `fn` | `(...args: any[]) => T` | | | `applyThis` | `any` | Optional. Default is `undefined`. | | `applyArgs` | `any[]` | Optional. Default is `undefined`. | Returns `T` | | runOutsideAngular() | | --- | | Executes the `fn` function synchronously in Angular's parent zone and returns value returned by the function. | | `runOutsideAngular<T>(fn: (...args: any[]) => T): T` Parameters | | | | | --- | --- | --- | | `fn` | `(...args: any[]) => T` | | Returns `T` | | Running functions via [runOutsideAngular](ngzone#runOutsideAngular) allows you to escape Angular's zone and do work that doesn't trigger Angular change-detection or is subject to Angular's error handling. Any future tasks or microtasks scheduled from within this function will continue executing from outside of the Angular zone. Use [run](ngzone#run) to reenter the Angular zone and do work that updates the application model. | Usage notes ----------- ### Example ``` import {Component, NgZone} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ selector: 'ng-zone-demo', template: ` <h2>Demo: NgZone</h2> <p>Progress: {{progress}}%</p> <p *ngIf="progress >= 100">Done processing {{label}} of Angular zone!</p> <button (click)="processWithinAngularZone()">Process within Angular zone</button> <button (click)="processOutsideOfAngularZone()">Process outside of Angular zone</button> `, }) export class NgZoneDemo { progress: number = 0; label: string; constructor(private _ngZone: NgZone) {} // Loop inside the Angular zone // so the UI DOES refresh after each setTimeout cycle processWithinAngularZone() { this.label = 'inside'; this.progress = 0; this._increaseProgress(() => console.log('Inside Done!')); } // Loop outside of the Angular zone // so the UI DOES NOT refresh after each setTimeout cycle processOutsideOfAngularZone() { this.label = 'outside'; this.progress = 0; this._ngZone.runOutsideAngular(() => { this._increaseProgress(() => { // reenter the Angular zone and display done this._ngZone.run(() => { console.log('Outside Done!'); }); }); }); } _increaseProgress(doneCallback: () => void) { this.progress += 1; console.log(`Current progress: ${this.progress}%`); if (this.progress < 100) { window.setTimeout(() => this._increaseProgress(doneCallback), 10); } else { doneCallback(); } } } ``` angular ClassSansProvider ClassSansProvider ================= `interface` Configures the `[Injector](injector)` to return a value by invoking a `useClass` function. Base for `[ClassProvider](classprovider)` decorator. ``` interface ClassSansProvider { useClass: Type<any> } ``` Child interfaces ---------------- * `[ClassProvider](classprovider)` See also -------- * ["Dependency Injection Guide"](../../guide/dependency-injection). Properties ---------- | Property | Description | | --- | --- | | `useClass: [Type](type)<any>` | Class to instantiate for the `token`. | angular asNativeElements asNativeElements ================ `function` ### `asNativeElements(debugEls: DebugElement[]): any` ###### Parameters | | | | | --- | --- | --- | | `debugEls` | `[DebugElement](debugelement)[]` | | ###### Returns `any` angular InjectorType InjectorType ============ `interface` A type which has an `InjectorDef` static field. [See more...](injectortype#description) ``` interface InjectorType<T> extends Type<T> { // inherited from core/Type constructor(...args: any[]): T } ``` Description ----------- `InjectorTypes` can be used to configure a `StaticInjector`. This is an opaque type whose structure is highly version dependent. Do not rely on any properties. angular DefaultIterableDiffer DefaultIterableDiffer ===================== `class` `deprecated` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` **Deprecated:** v4.0.0 - Should not be part of public API. ``` class DefaultIterableDiffer<V> implements IterableDiffer<V>, IterableChanges<V> { constructor(trackByFn?: TrackByFunction<V>) length: number collection: V[] | Iterable<V> | null isDirty: boolean forEachItem(fn: (record: IterableChangeRecord_<V>) => void) forEachOperation(fn: (item: IterableChangeRecord<V>, previousIndex: number, currentIndex: number) => void) forEachPreviousItem(fn: (record: IterableChangeRecord_<V>) => void) forEachAddedItem(fn: (record: IterableChangeRecord_<V>) => void) forEachMovedItem(fn: (record: IterableChangeRecord_<V>) => void) forEachRemovedItem(fn: (record: IterableChangeRecord_<V>) => void) forEachIdentityChange(fn: (record: IterableChangeRecord_<V>) => void) diff(collection: NgIterable<V>): DefaultIterableDiffer<V> | null onDestroy() check(collection: NgIterable<V>): boolean } ``` Constructor ----------- | | | | | | --- | --- | --- | --- | | `constructor(trackByFn?: TrackByFunction<V>)` Parameters | | | | | --- | --- | --- | | `trackByFn` | `[TrackByFunction](trackbyfunction)<V>` | Optional. Default is `undefined`. | | Properties ---------- | Property | Description | | --- | --- | | `length: number` | Read-Only | | `collection: V[] | Iterable<V> | null` | Read-Only | | `isDirty: boolean` | Read-Only | Methods ------- | forEachItem() | | --- | | `forEachItem(fn: (record: IterableChangeRecord_<V>) => void)` Parameters | | | | | --- | --- | --- | | `fn` | `(record: IterableChangeRecord_<V>) => void` | | | | forEachOperation() | | --- | | `forEachOperation(fn: (item: IterableChangeRecord<V>, previousIndex: number, currentIndex: number) => void)` Parameters | | | | | --- | --- | --- | | `fn` | `(item: [IterableChangeRecord](iterablechangerecord)<V>, previousIndex: number, currentIndex: number) => void` | | | | forEachPreviousItem() | | --- | | `forEachPreviousItem(fn: (record: IterableChangeRecord_<V>) => void)` Parameters | | | | | --- | --- | --- | | `fn` | `(record: IterableChangeRecord_<V>) => void` | | | | forEachAddedItem() | | --- | | `forEachAddedItem(fn: (record: IterableChangeRecord_<V>) => void)` Parameters | | | | | --- | --- | --- | | `fn` | `(record: IterableChangeRecord_<V>) => void` | | | | forEachMovedItem() | | --- | | `forEachMovedItem(fn: (record: IterableChangeRecord_<V>) => void)` Parameters | | | | | --- | --- | --- | | `fn` | `(record: IterableChangeRecord_<V>) => void` | | | | forEachRemovedItem() | | --- | | `forEachRemovedItem(fn: (record: IterableChangeRecord_<V>) => void)` Parameters | | | | | --- | --- | --- | | `fn` | `(record: IterableChangeRecord_<V>) => void` | | | | forEachIdentityChange() | | --- | | `forEachIdentityChange(fn: (record: IterableChangeRecord_<V>) => void)` Parameters | | | | | --- | --- | --- | | `fn` | `(record: IterableChangeRecord_<V>) => void` | | | | diff() | | --- | | `diff(collection: NgIterable<V>): DefaultIterableDiffer<V> | null` Parameters | | | | | --- | --- | --- | | `collection` | `[NgIterable](ngiterable)<V>` | | Returns `[DefaultIterableDiffer](defaultiterablediffer)<V> | null` | | onDestroy() | | --- | | `onDestroy()` Parameters There are no parameters. | | check() | | --- | | `check(collection: NgIterable<V>): boolean` Parameters | | | | | --- | --- | --- | | `collection` | `[NgIterable](ngiterable)<V>` | | Returns `boolean` |
programming_docs
angular Pipe Pipe ==== `decorator` Decorator that marks a class as pipe and supplies configuration metadata. [See more...](pipe#description) | Option | Description | | --- | --- | | [`name`](pipe#name) | The pipe name to use in template bindings. Typically uses [lowerCamelCase](../../guide/glossary#case-types) because the name cannot contain hyphens. | | [`pure?`](pipe#pure) | When true, the pipe is pure, meaning that the `transform()` method is invoked only when its input arguments change. Pipes are pure by default. | | [`standalone?`](pipe#standalone) | Angular pipes marked as `standalone` do not need to be declared in an NgModule. Such pipes don't depend on any "intermediate context" of an NgModule (ex. configured providers). | See also -------- * [Style Guide: Pipe Names](../../guide/styleguide#02-09) Description ----------- A pipe class must implement the `[PipeTransform](pipetransform)` interface. For example, if the name is "myPipe", use a template binding expression such as the following: ``` {{ exp | myPipe }} ``` The result of the expression is passed to the pipe's `transform()` method. A pipe must belong to an NgModule in order for it to be available to a template. To make it a member of an NgModule, list it in the `declarations` field of the `[NgModule](ngmodule)` metadata. Options ------- | name | | --- | | The pipe name to use in template bindings. Typically uses [lowerCamelCase](../../guide/glossary#case-types) because the name cannot contain hyphens. | | `name: string` | | | | pure | | --- | | When true, the pipe is pure, meaning that the `transform()` method is invoked only when its input arguments change. Pipes are pure by default. | | `pure?: boolean` | | If the pipe has internal state (that is, the result depends on state other than its arguments), set `pure` to false. In this case, the pipe is invoked on each change-detection cycle, even if the arguments have not changed. | | standalone | | --- | | Angular pipes marked as `standalone` do not need to be declared in an NgModule. Such pipes don't depend on any "intermediate context" of an NgModule (ex. configured providers). | | `standalone?: boolean` | | More information about standalone components, directives, and pipes can be found in [this guide](../../guide/standalone-components). | angular NO_ERRORS_SCHEMA NO\_ERRORS\_SCHEMA ================== `const` Defines a schema that allows any property on any element. [See more...](no_errors_schema#description) ### `const NO_ERRORS_SCHEMA: SchemaMetadata;` #### Description This schema allows you to ignore the errors related to any unknown elements or properties in a template. The usage of this schema is generally discouraged because it prevents useful validation and may hide real errors in your template. Consider using the `[CUSTOM\_ELEMENTS\_SCHEMA](custom_elements_schema)` instead. angular Predicate Predicate ========= `interface` A boolean-valued function over a value, possibly including context information regarding that value's position in an array. ``` interface Predicate<T> { (value: T): boolean } ``` Methods ------- | *call signature* | | --- | | `(value: T): boolean` Parameters | | | | | --- | --- | --- | | `value` | `T` | | Returns `boolean` | angular enableProdMode enableProdMode ============== `function` Disable Angular's development mode, which turns off assertions and other checks within the framework. [See more...](enableprodmode#description) ### `enableProdMode(): void` ###### Parameters There are no parameters. ###### Returns `void` See also -------- * [ng build](cli/build) Description ----------- One important assertion this disables verifies that a change detection pass does not result in additional changes to any bindings (also known as unidirectional data flow). Using this method is discouraged as the Angular CLI will set production mode when using the `optimization` option. angular DebugEventListener DebugEventListener ================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` ``` class DebugEventListener { constructor(name: string, callback: Function) name: string callback: Function } ``` Constructor ----------- | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | | `constructor(name: string, callback: Function)` Parameters | | | | | --- | --- | --- | | `name` | `string` | | | `callback` | `Function` | | | Properties ---------- | Property | Description | | --- | --- | | `name: string` | Declared in Constructor | | `callback: Function` | Declared in Constructor | angular ViewContainerRef ViewContainerRef ================ `class` Represents a container where one or more views can be attached to a component. [See more...](viewcontainerref#description) ``` abstract class ViewContainerRef { abstract element: ElementRef abstract injector: Injector abstract parentInjector: Injector abstract length: number abstract clear(): void abstract get(index: number): ViewRef | null abstract createEmbeddedView<C>(templateRef: TemplateRef<C>, context?: C, options?: { index?: number; injector?: Injector; }): EmbeddedViewRef<C> abstract createComponent<C>(componentType: Type<C>, options?: { index?: number; injector?: Injector; ngModuleRef?: NgModuleRef<unknown>; environmentInjector?: EnvironmentInjector | NgModuleRef<unknown>; projectableNodes?: Node[][]; }): ComponentRef<C> abstract insert(viewRef: ViewRef, index?: number): ViewRef abstract move(viewRef: ViewRef, currentIndex: number): ViewRef abstract indexOf(viewRef: ViewRef): number abstract remove(index?: number): void abstract detach(index?: number): ViewRef | null } ``` See also -------- * `[ComponentRef](componentref)` * `[EmbeddedViewRef](embeddedviewref)` Description ----------- Can contain *host views* (created by instantiating a component with the `[createComponent](createcomponent)()` method), and *embedded views* (created by instantiating a `[TemplateRef](templateref)` with the `createEmbeddedView()` method). A view container instance can contain other view containers, creating a [view hierarchy](../../guide/glossary#view-tree). Properties ---------- | Property | Description | | --- | --- | | `abstract element: [ElementRef](elementref)` | Read-Only Anchor element that specifies the location of this container in the containing view. Each view container can have only one anchor element, and each anchor element can have only a single view container. Root elements of views attached to this container become siblings of the anchor element in the rendered view. Access the `[ViewContainerRef](viewcontainerref)` of an element by placing a `[Directive](directive)` injected with `[ViewContainerRef](viewcontainerref)` on the element, or use a `[ViewChild](viewchild)` query. | | `abstract injector: [Injector](injector)` | Read-Only The [dependency injector](../../guide/glossary#injector) for this view container. | | `abstract parentInjector: [Injector](injector)` | Read-Only **Deprecated** No replacement | | `abstract length: number` | Read-Only Reports how many views are currently attached to this container. | Methods ------- | clear() | | --- | | Destroys all views in this container. | | `abstract clear(): void` Parameters There are no parameters. Returns `void` | | get() | | --- | | Retrieves a view from this container. | | `abstract get(index: number): ViewRef | null` Parameters | | | | | --- | --- | --- | | `index` | `number` | The 0-based index of the view to retrieve. | Returns `[ViewRef](viewref) | null`: The `[ViewRef](viewref)` instance, or null if the index is out of range. | | createEmbeddedView() | | --- | | Instantiates an embedded view and inserts it into this container. | | `abstract createEmbeddedView<C>(templateRef: TemplateRef<C>, context?: C, options?: { index?: number; injector?: Injector; }): EmbeddedViewRef<C>` Parameters | | | | | --- | --- | --- | | `templateRef` | `[TemplateRef<C>](templateref)` | The HTML template that defines the view. | | `context` | `C` | The data-binding context of the embedded view, as declared in the `[<ng-template>](ng-template)` usage. Optional. Default is `undefined`. | | `options` | `object` | Extra configuration for the created view. Includes:* index: The 0-based index at which to insert the new view into this container. If not specified, appends the new view as the last entry. * injector: Injector to be used within the embedded view. Optional. Default is `undefined`. | Returns `[EmbeddedViewRef<C>](embeddedviewref)`: The `[ViewRef](viewref)` instance for the newly created view. | | `abstract createEmbeddedView<C>(templateRef: TemplateRef<C>, context?: C, index?: number): EmbeddedViewRef<C>` Parameters | | | | | --- | --- | --- | | `templateRef` | `[TemplateRef<C>](templateref)` | The HTML template that defines the view. | | `context` | `C` | The data-binding context of the embedded view, as declared in the `[<ng-template>](ng-template)` usage. Optional. Default is `undefined`. | | `index` | `number` | The 0-based index at which to insert the new view into this container. If not specified, appends the new view as the last entry. Optional. Default is `undefined`. | Returns `[EmbeddedViewRef<C>](embeddedviewref)`: The `[ViewRef](viewref)` instance for the newly created view. | | createComponent() | | --- | | Instantiates a single component and inserts its host view into this container. | | `abstract createComponent<C>(componentType: Type<C>, options?: { index?: number; injector?: Injector; ngModuleRef?: NgModuleRef<unknown>; environmentInjector?: EnvironmentInjector | NgModuleRef<unknown>; projectableNodes?: Node[][]; }): ComponentRef<C>` Parameters | | | | | --- | --- | --- | | `componentType` | `[Type](type)<C>` | Component Type to use. | | `options` | `object` | An object that contains extra parameters:* index: the index at which to insert the new component's host view into this container. If not specified, appends the new view as the last entry. * injector: the injector to use as the parent for the new component. * ngModuleRef: an NgModuleRef of the component's NgModule, you should almost always provide this to ensure that all expected providers are available for the component instantiation. * environmentInjector: an EnvironmentInjector which will provide the component's environment. you should almost always provide this to ensure that all expected providers are available for the component instantiation. This option is intended to replace the `ngModuleRef` parameter. * projectableNodes: list of DOM nodes that should be projected through [`<ng-content>`](ng-content) of the new component instance. Optional. Default is `undefined`. | Returns `[ComponentRef<C>](componentref)`: The new `[ComponentRef](componentref)` which contains the component instance and the host view. | | `abstract createComponent<C>(componentFactory: ComponentFactory<C>, index?: number, injector?: Injector, projectableNodes?: any[][], environmentInjector?: EnvironmentInjector | NgModuleRef<any>): ComponentRef<C>` **Deprecated** Angular no longer requires component factories to dynamically create components. Use different signature of the `[createComponent](createcomponent)` method, which allows passing Component class directly. Parameters | | | | | --- | --- | --- | | `componentFactory` | `[ComponentFactory<C>](componentfactory)` | Component factory to use. | | `index` | `number` | The index at which to insert the new component's host view into this container. If not specified, appends the new view as the last entry. Optional. Default is `undefined`. | | `injector` | `[Injector](injector)` | The injector to use as the parent for the new component. Optional. Default is `undefined`. | | `projectableNodes` | `any[][]` | List of DOM nodes that should be projected through [`<ng-content>`](ng-content) of the new component instance. Optional. Default is `undefined`. | | `environmentInjector` | `[EnvironmentInjector](environmentinjector) | [NgModuleRef](ngmoduleref)<any>` | Optional. Default is `undefined`. | Returns `[ComponentRef<C>](componentref)`: The new `[ComponentRef](componentref)` which contains the component instance and the host view. | | insert() | | --- | | Inserts a view into this container. | | `abstract insert(viewRef: ViewRef, index?: number): ViewRef` Parameters | | | | | --- | --- | --- | | `viewRef` | `[ViewRef](viewref)` | The view to insert. | | `index` | `number` | The 0-based index at which to insert the view. If not specified, appends the new view as the last entry. Optional. Default is `undefined`. | Returns `[ViewRef](viewref)`: The inserted `[ViewRef](viewref)` instance. | | move() | | --- | | Moves a view to a new location in this container. | | `abstract move(viewRef: ViewRef, currentIndex: number): ViewRef` Parameters | | | | | --- | --- | --- | | `viewRef` | `[ViewRef](viewref)` | The view to move. | | `currentIndex` | `number` | | Returns `[ViewRef](viewref)`: The moved `[ViewRef](viewref)` instance. | | indexOf() | | --- | | Returns the index of a view within the current container. | | `abstract indexOf(viewRef: ViewRef): number` Parameters | | | | | --- | --- | --- | | `viewRef` | `[ViewRef](viewref)` | The view to query. | Returns `number`: The 0-based index of the view's position in this container, or `-1` if this container doesn't contain the view. | | remove() | | --- | | Destroys a view attached to this container | | `abstract remove(index?: number): void` Parameters | | | | | --- | --- | --- | | `index` | `number` | The 0-based index of the view to destroy. If not specified, the last view in the container is removed. Optional. Default is `undefined`. | Returns `void` | | detach() | | --- | | Detaches a view from this container without destroying it. Use along with `insert()` to move a view within the current container. | | `abstract detach(index?: number): ViewRef | null` Parameters | | | | | --- | --- | --- | | `index` | `number` | The 0-based index of the view to detach. If not specified, the last view in the container is detached. Optional. Default is `undefined`. | Returns `[ViewRef](viewref) | null` | angular Directive Directive ========= `decorator` Decorator that marks a class as an Angular directive. You can define your own directives to attach custom behavior to elements in the DOM. [See more...](directive#description) | Option | Description | | --- | --- | | [`selector?`](directive#selector) | The CSS selector that identifies this directive in a template and triggers instantiation of the directive. | | [`inputs?`](directive#inputs) | Enumerates the set of data-bound input properties for a directive | | [`outputs?`](directive#outputs) | Enumerates the set of event-bound output properties. | | [`providers?`](directive#providers) | Configures the [injector](../../guide/glossary#injector) of this directive or component with a [token](../../guide/glossary#di-token) that maps to a [provider](../../guide/glossary#provider) of a dependency. | | [`exportAs?`](directive#exportAs) | Defines the name that can be used in the template to assign this directive to a variable. | | [`queries?`](directive#queries) | Configures the queries that will be injected into the directive. | | [`host?`](directive#host) | Maps class properties to host element bindings for properties, attributes, and events, using a set of key-value pairs. | | [`jit?`](directive#jit) | When present, this directive/component is ignored by the AOT compiler. It remains in distributed code, and the JIT compiler attempts to compile it at run time, in the browser. To ensure the correct behavior, the app must import `@angular/compiler`. | | [`standalone?`](directive#standalone) | Angular directives marked as `standalone` do not need to be declared in an NgModule. Such directives don't depend on any "intermediate context" of an NgModule (ex. configured providers). | | [`hostDirectives?`](directive#hostDirectives) | Standalone directives that should be applied to the host whenever the directive is matched. By default, none of the inputs or outputs of the host directives will be available on the host, unless they are specified in the `inputs` or `outputs` properties. | Subclasses ---------- * `[Component](component)` Description ----------- The options provide configuration metadata that determines how the directive should be processed, instantiated and used at runtime. Directive classes, like component classes, can implement [life-cycle hooks](../../guide/lifecycle-hooks) to influence their configuration and behavior. Further information is available in the [Usage Notes...](directive#usage-notes) Options ------- | selector | | --- | | The CSS selector that identifies this directive in a template and triggers instantiation of the directive. | | `selector?: string` | | Declare as one of the following:* `element-name`: Select by element name. * `.class`: Select by class name. * `[attribute]`: Select by attribute name. * `[attribute=value]`: Select by attribute name and value. * `:not(sub_selector)`: Select only if the element does not match the `sub_selector`. * `selector1, selector2`: Select if either `selector1` or `selector2` matches. Angular only allows directives to apply on CSS selectors that do not cross element boundaries. For the following template HTML, a directive with an `input[type=text]` selector, would be instantiated only on the `<input type="text">` element. ``` <form> <input type="text"> <input type="radio"> <form> ``` | | inputs | | --- | | Enumerates the set of data-bound input properties for a directive | | `inputs?: string[]` | | Angular automatically updates input properties during change detection. The `inputs` property defines a set of `directiveProperty` to `bindingProperty` configuration:* `directiveProperty` specifies the component property where the value is written. * `bindingProperty` specifies the DOM property where the value is read from. When `bindingProperty` is not provided, it is assumed to be equal to `directiveProperty`. The following example creates a component with two data-bound properties. ``` @Component({ selector: 'bank-account', inputs: ['bankName', 'id: account-id'], template: ` Bank Name: {{bankName}} Account Id: {{id}} ` }) class BankAccount { bankName: string; id: string; } ``` | | outputs | | --- | | Enumerates the set of event-bound output properties. | | `outputs?: string[]` | | When an output property emits an event, an event handler attached to that event in the template is invoked. The `outputs` property defines a set of `directiveProperty` to `bindingProperty` configuration:* `directiveProperty` specifies the component property that emits events. * `bindingProperty` specifies the DOM property the event handler is attached to. ``` @Component({ selector: 'child-dir', outputs: [ 'bankNameChange' ], template: `<input (input)="bankNameChange.emit($event.target.value)" />` }) class ChildDir { bankNameChange: EventEmitter<string> = new EventEmitter<string>(); } @Component({ selector: 'main', template: ` {{ bankName }} <child-dir (bankNameChange)="onBankNameChange($event)"></child-dir> ` }) class MainComponent { bankName: string; onBankNameChange(bankName: string) { this.bankName = bankName; } } ``` | | providers | | --- | | Configures the [injector](../../guide/glossary#injector) of this directive or component with a [token](../../guide/glossary#di-token) that maps to a [provider](../../guide/glossary#provider) of a dependency. | | `providers?: Provider[]` | | | | exportAs | | --- | | Defines the name that can be used in the template to assign this directive to a variable. | | `exportAs?: string` | | ``` @Directive({ selector: 'child-dir', exportAs: 'child' }) class ChildDir { } @Component({ selector: 'main', template: `<child-dir #c="child"></child-dir>` }) class MainComponent { } ``` | | queries | | --- | | Configures the queries that will be injected into the directive. | | `queries?: { [key: string]: any; }` | | Content queries are set before the `ngAfterContentInit` callback is called. View queries are set before the `ngAfterViewInit` callback is called. The following example shows how queries are defined and when their results are available in lifecycle hooks: ``` @Component({ selector: 'someDir', queries: { contentChildren: new ContentChildren(ChildDirective), viewChildren: new ViewChildren(ChildDirective) }, template: '<child-directive></child-directive>' }) class SomeDir { contentChildren: QueryList<ChildDirective>, viewChildren: QueryList<ChildDirective> ngAfterContentInit() { // contentChildren is set } ngAfterViewInit() { // viewChildren is set } } ``` | | host | | --- | | Maps class properties to host element bindings for properties, attributes, and events, using a set of key-value pairs. | | `host?: { [key: string]: string; }` | | Angular automatically checks host property bindings during change detection. If a binding changes, Angular updates the directive's host element. When the key is a property of the host element, the property value is the propagated to the specified DOM property. When the key is a static attribute in the DOM, the attribute value is propagated to the specified property in the host element. For event handling:* The key is the DOM event that the directive listens to. To listen to global events, add the target to the event name. The target can be `window`, `document` or `body`. * The value is the statement to execute when the event occurs. If the statement evaluates to `false`, then `preventDefault` is applied on the DOM event. A handler method can refer to the `$event` local variable. | | jit | | --- | | When present, this directive/component is ignored by the AOT compiler. It remains in distributed code, and the JIT compiler attempts to compile it at run time, in the browser. To ensure the correct behavior, the app must import `@angular/compiler`. | | `jit?: true` | | | | standalone | | --- | | Angular directives marked as `standalone` do not need to be declared in an NgModule. Such directives don't depend on any "intermediate context" of an NgModule (ex. configured providers). | | `standalone?: boolean` | | More information about standalone components, directives, and pipes can be found in [this guide](../../guide/standalone-components). | | hostDirectives | | --- | | Standalone directives that should be applied to the host whenever the directive is matched. By default, none of the inputs or outputs of the host directives will be available on the host, unless they are specified in the `inputs` or `outputs` properties. | | `hostDirectives?: (Type<unknown> | { directive: Type<unknown>; inputs?: string[]; outputs?: string[]; })[]` | | You can additionally alias inputs and outputs by putting a colon and the alias after the original input or output name. For example, if a directive applied via `hostDirectives` defines an input named `menuDisabled`, you can alias this to `disabled` by adding `'menuDisabled: disabled'` as an entry to `inputs`. | Usage notes ----------- To define a directive, mark the class with the decorator and provide metadata. ``` import {Directive} from '@angular/core'; @Directive({ selector: 'my-directive', }) export class MyDirective { ... } ``` ### Declaring directives In order to make a directive available to other components in your application, you should do one of the following: * either mark the directive as [standalone](../../guide/standalone-components), * or declare it in an NgModule by adding it to the `declarations` and `exports` fields. **Marking a directive as standalone** You can add the `standalone: true` flag to the Directive decorator metadata to declare it as [standalone](../../guide/standalone-components): ``` @Directive({ standalone: true, selector: 'my-directive', }) class MyDirective {} ``` When marking a directive as standalone, please make sure that the directive is not already declared in an NgModule. **Declaring a directive in an NgModule** Another approach is to declare a directive in an NgModule: ``` @Directive({ selector: 'my-directive', }) class MyDirective {} @NgModule({ declarations: [MyDirective, SomeComponent], exports: [MyDirective], // making it available outside of this module }) class SomeNgModule {} ``` When declaring a directive in an NgModule, please make sure that: * the directive is declared in exactly one NgModule. * the directive is not standalone. * you do not re-declare a directive imported from another module. * the directive is included into the `exports` field as well if you want this directive to be accessible for components outside of the NgModule.
programming_docs
angular EventEmitter EventEmitter ============ `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Use in components with the `@[Output](output)` directive to emit custom events synchronously or asynchronously, and register handlers for those events by subscribing to an instance. ``` class EventEmitter<T> extends Subject<T> { constructor(isAsync?: boolean): EventEmitter<T> emit(value?: T): void subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription } ``` See also -------- * [Observables in Angular](../../guide/observables-in-angular) Constructor ----------- | | | --- | | Creates an instance of this class that can deliver events synchronously or asynchronously. This class is "final" and should not be extended. See the [public API notes](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes). | | `constructor(isAsync?: boolean): EventEmitter<T>` Parameters | | | | | --- | --- | --- | | `isAsync` | `boolean` | When true, deliver events asynchronously. Optional. Default is `false`. | Returns `[EventEmitter<T>](eventemitter)` | Methods ------- | emit() | | --- | | Emits an event containing a given value. | | `emit(value?: T): void` Parameters | | | | | --- | --- | --- | | `value` | `T` | The value to emit. Optional. Default is `undefined`. | Returns `void` | | subscribe() | | --- | | Registers handlers for events emitted by this instance. | | `subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription` Parameters | | | | | --- | --- | --- | | `next` | `(value: T) => void` | When supplied, a custom handler for emitted events. Optional. Default is `undefined`. | | `error` | `(error: any) => void` | When supplied, a custom handler for an error notification from this emitter. Optional. Default is `undefined`. | | `complete` | `() => void` | When supplied, a custom handler for a completion notification from this emitter. Optional. Default is `undefined`. | Returns `Subscription` | | `subscribe(observerOrNext?: any, error?: any, complete?: any): Subscription` Parameters | | | | | --- | --- | --- | | `observerOrNext` | `any` | When supplied, a custom handler for emitted events, or an observer object. Optional. Default is `undefined`. | | `error` | `any` | When supplied, a custom handler for an error notification from this emitter. Optional. Default is `undefined`. | | `complete` | `any` | When supplied, a custom handler for a completion notification from this emitter. Optional. Default is `undefined`. | Returns `Subscription` | Usage notes ----------- Extends [RxJS `Subject`](https://rxjs.dev/api/index/class/Subject) for Angular by adding the `emit()` method. In the following example, a component defines two output properties that create event emitters. When the title is clicked, the emitter emits an open or close event to toggle the current visibility state. ``` @Component({ selector: 'zippy', template: ` <div class="zippy"> <div (click)="toggle()">Toggle</div> <div [hidden]="!visible"> <ng-content></ng-content> </div> </div>`}) export class Zippy { visible: boolean = true; @Output() open: EventEmitter<any> = new EventEmitter(); @Output() close: EventEmitter<any> = new EventEmitter(); toggle() { this.visible = !this.visible; if (this.visible) { this.open.emit(null); } else { this.close.emit(null); } } } ``` Access the event object with the `$event` argument passed to the output event handler: ``` <zippy (open)="onOpen($event)" (close)="onClose($event)"></zippy> ``` angular CUSTOM_ELEMENTS_SCHEMA CUSTOM\_ELEMENTS\_SCHEMA ======================== `const` Defines a schema that allows an NgModule to contain the following: * Non-Angular elements named with dash case (`-`). * Element properties named with dash case (`-`). Dash case is the naming convention for custom elements. ### `const CUSTOM_ELEMENTS_SCHEMA: SchemaMetadata;` angular ViewChildren ViewChildren ============ `decorator` Property decorator that configures a view query. [See more...](viewchildren#description) Description ----------- Use to get the `[QueryList](querylist)` of elements or directives from the view DOM. Any time a child element is added, removed, or moved, the query list will be updated, and the changes observable of the query list will emit a new value. View queries are set before the `ngAfterViewInit` callback is called. **Metadata Properties**: * **selector** - The directive type or the name used for querying. * **read** - Used to read a different token from the queried elements. * **emitDistinctChangesOnly** - The `[QueryList](querylist)#changes` observable will emit new values only if the QueryList result has changed. When `false` the `changes` observable might emit even if the QueryList has not changed. **Note: \*** This config option is **deprecated**, it will be permanently set to `true` and removed in future versions of Angular. The following selectors are supported. * Any class with the `@[Component](component)` or `@[Directive](directive)` decorator * A template reference variable as a string (e.g. query `<my-component #cmp></my-component>` with `@[ViewChildren](viewchildren)('cmp')`) * Any provider defined in the child component tree of the current component (e.g. `@[ViewChildren](viewchildren)(SomeService) someService!: SomeService`) * Any provider defined through a string token (e.g. `@[ViewChildren](viewchildren)('someToken') someTokenVal!: any`) * A `[TemplateRef](templateref)` (e.g. query `<ng-template></ng-template>` with `@[ViewChildren](viewchildren)([TemplateRef](templateref)) template;`) In addition, multiple string selectors can be separated with a comma (e.g. `@[ViewChildren](viewchildren)('cmp1,cmp2')`) The following values are supported by `read`: * Any class with the `@[Component](component)` or `@[Directive](directive)` decorator * Any provider defined on the injector of the component that is matched by the `selector` of this query * Any provider defined through a string token (e.g. `{provide: 'token', useValue: 'val'}`) * `[TemplateRef](templateref)`, `[ElementRef](elementref)`, and `[ViewContainerRef](viewcontainerref)` Further information is available in the [Usage Notes...](viewchildren#usage-notes) Options ------- Usage notes ----------- ``` import {AfterViewInit, Component, Directive, QueryList, ViewChildren} from '@angular/core'; @Directive({selector: 'child-directive'}) class ChildDirective { } @Component({selector: 'someCmp', templateUrl: 'someCmp.html'}) class SomeCmp implements AfterViewInit { @ViewChildren(ChildDirective) viewChildren!: QueryList<ChildDirective>; ngAfterViewInit() { // viewChildren is set } } ``` ### Another example ``` import {AfterViewInit, Component, Directive, Input, QueryList, ViewChildren} from '@angular/core'; @Directive({selector: 'pane'}) export class Pane { @Input() id!: string; } @Component({ selector: 'example-app', template: ` <pane id="1"></pane> <pane id="2"></pane> <pane id="3" *ngIf="shouldShow"></pane> <button (click)="show()">Show 3</button> <div>panes: {{serializedPanes}}</div> `, }) export class ViewChildrenComp implements AfterViewInit { @ViewChildren(Pane) panes!: QueryList<Pane>; serializedPanes: string = ''; shouldShow = false; show() { this.shouldShow = true; } ngAfterViewInit() { this.calculateSerializedPanes(); this.panes.changes.subscribe((r) => { this.calculateSerializedPanes(); }); } calculateSerializedPanes() { setTimeout(() => { this.serializedPanes = this.panes.map(p => p.id).join(', '); }, 0); } } ``` angular ValueSansProvider ValueSansProvider ================= `interface` Configures the `[Injector](injector)` to return a value for a token. Base for `[ValueProvider](valueprovider)` decorator. ``` interface ValueSansProvider { useValue: any } ``` Child interfaces ---------------- * `[ValueProvider](valueprovider)` Properties ---------- | Property | Description | | --- | --- | | `useValue: any` | The value to inject. | angular IterableChangeRecord IterableChangeRecord ==================== `interface` Record representing the item change information. ``` interface IterableChangeRecord<V> { currentIndex: number | null previousIndex: number | null item: V trackById: any } ``` Properties ---------- | Property | Description | | --- | --- | | `currentIndex: number | null` | Read-Only Current index of the item in `Iterable` or null if removed. | | `previousIndex: number | null` | Read-Only Previous index of the item in `Iterable` or null if added. | | `item: V` | Read-Only The item. | | `trackById: any` | Read-Only Track by identity as computed by the `[TrackByFunction](trackbyfunction)`. | angular SecurityContext SecurityContext =============== `enum` A SecurityContext marks a location that has dangerous security implications, e.g. a DOM property like `innerHTML` that could cause Cross Site Scripting (XSS) security bugs when improperly handled. [See more...](securitycontext#description) ``` enum SecurityContext { NONE: 0 HTML: 1 STYLE: 2 SCRIPT: 3 URL: 4 RESOURCE_URL: 5 } ``` Description ----------- See DomSanitizer for more details on security in Angular applications. Members ------- | Member | Description | | --- | --- | | `NONE: 0` | | | `HTML: 1` | | | `STYLE: 2` | | | `SCRIPT: 3` | | | `URL: 4` | | | `RESOURCE\_URL: 5` | | angular ApplicationRef ApplicationRef ============== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A reference to an Angular application running on a page. ``` class ApplicationRef { destroyed componentTypes: Type<any>[] components: ComponentRef<any>[] isStable: Observable<boolean> injector: EnvironmentInjector viewCount bootstrap<C>(componentOrFactory: ComponentFactory<C> | Type<C>, rootSelectorOrNode?: any): ComponentRef<C> tick(): void attachView(viewRef: ViewRef): void detachView(viewRef: ViewRef): void destroy(): void } ``` Provided in ----------- * ``` 'root' ``` Properties ---------- | Property | Description | | --- | --- | | `destroyed` | Read-Only Indicates whether this instance was destroyed. | | `componentTypes: [Type](type)<any>[]` | Read-Only Get a list of component types registered to this application. This list is populated even before the component is created. | | `components: [ComponentRef](componentref)<any>[]` | Read-Only Get a list of components registered to this application. | | `isStable: Observable<boolean>` | Read-Only Returns an Observable that indicates when the application is stable or unstable. See also:* [Usage notes](applicationref#is-stable-examples) for examples and caveats when using this API. | | `injector: [EnvironmentInjector](environmentinjector)` | Read-Only The `[EnvironmentInjector](environmentinjector)` used to create this application. | | `viewCount` | Read-Only Returns the number of attached views. | Methods ------- | bootstrap() | | --- | | Bootstrap a component onto the element identified by its selector or, optionally, to a specified element. | | `bootstrap<C>(component: Type<C>, rootSelectorOrNode?: any): ComponentRef<C>` Parameters | | | | | --- | --- | --- | | `component` | `[Type](type)<C>` | | | `rootSelectorOrNode` | `any` | Optional. Default is `undefined`. | Returns `[ComponentRef<C>](componentref)` | | `bootstrap<C>(componentFactory: ComponentFactory<C>, rootSelectorOrNode?: any): ComponentRef<C>` **Deprecated** Passing Component factories as the `Application.bootstrap` function argument is deprecated. Pass Component Types instead. Parameters | | | | | --- | --- | --- | | `componentFactory` | `[ComponentFactory<C>](componentfactory)` | | | `rootSelectorOrNode` | `any` | Optional. Default is `undefined`. | Returns `[ComponentRef<C>](componentref)` | | Usage Notes Bootstrap process When bootstrapping a component, Angular mounts it onto a target DOM element and kicks off automatic change detection. The target DOM element can be provided using the `rootSelectorOrNode` argument. If the target DOM element is not provided, Angular tries to find one on a page using the `selector` of the component that is being bootstrapped (first matched element is used). Example Generally, we define the component to bootstrap in the `bootstrap` array of `[NgModule](ngmodule)`, but it requires us to know the component while writing the application code. Imagine a situation where we have to wait for an API call to decide about the component to bootstrap. We can use the `ngDoBootstrap` hook of the `[NgModule](ngmodule)` and call this method to dynamically bootstrap a component. ``` ngDoBootstrap(appRef: ApplicationRef) { this.fetchDataFromApi().then((componentName: string) => { if (componentName === 'ComponentOne') { appRef.bootstrap(ComponentOne); } else { appRef.bootstrap(ComponentTwo); } }); } ``` Optionally, a component can be mounted onto a DOM element that does not match the selector of the bootstrapped component. In the following example, we are providing a CSS selector to match the target element. ``` ngDoBootstrap(appRef: ApplicationRef) { appRef.bootstrap(ComponentThree, '#root-element'); } ``` While in this example, we are providing reference to a DOM node. ``` ngDoBootstrap(appRef: ApplicationRef) { const element = document.querySelector('#root-element'); appRef.bootstrap(ComponentFour, element); } ``` | | tick() | | --- | | Invoke this method to explicitly process change detection and its side-effects. | | `tick(): void` Parameters There are no parameters. Returns `void` | | In development mode, `[tick](testing/tick)()` also performs a second change detection cycle to ensure that no further changes are detected. If additional changes are picked up during this second cycle, bindings in the app have side-effects that cannot be resolved in a single change detection pass. In this case, Angular throws an error, since an Angular application can only have one change detection pass during which all change detection must complete. | | attachView() | | --- | | Attaches a view so that it will be dirty checked. The view will be automatically detached when it is destroyed. This will throw if the view is already attached to a ViewContainer. | | `attachView(viewRef: ViewRef): void` Parameters | | | | | --- | --- | --- | | `viewRef` | `[ViewRef](viewref)` | | Returns `void` | | detachView() | | --- | | Detaches a view from dirty checking again. | | `detachView(viewRef: ViewRef): void` Parameters | | | | | --- | --- | --- | | `viewRef` | `[ViewRef](viewref)` | | Returns `void` | | destroy() | | --- | | Destroys an Angular application represented by this `[ApplicationRef](applicationref)`. Calling this function will destroy the associated environment injectors as well as all the bootstrapped components with their views. | | `destroy(): void` Parameters There are no parameters. Returns `void` | Usage notes ----------- ### isStable examples and caveats Note two important points about `isStable`, demonstrated in the examples below: * the application will never be stable if you start any kind of recurrent asynchronous task when the application starts (for example for a polling process, started with a `setInterval`, a `setTimeout` or using RxJS operators like `interval`); * the `isStable` Observable runs outside of the Angular zone. Let's imagine that you start a recurrent task (here incrementing a counter, using RxJS `interval`), and at the same time subscribe to `isStable`. ``` constructor(appRef: ApplicationRef) { appRef.isStable.pipe( filter(stable => stable) ).subscribe(() => console.log('App is stable now'); interval(1000).subscribe(counter => console.log(counter)); } ``` In this example, `isStable` will never emit `true`, and the trace "App is stable now" will never get logged. If you want to execute something when the app is stable, you have to wait for the application to be stable before starting your polling process. ``` constructor(appRef: ApplicationRef) { appRef.isStable.pipe( first(stable => stable), tap(stable => console.log('App is stable now')), switchMap(() => interval(1000)) ).subscribe(counter => console.log(counter)); } ``` In this example, the trace "App is stable now" will be logged and then the counter starts incrementing every second. Note also that this Observable runs outside of the Angular zone, which means that the code in the subscription to this Observable will not trigger the change detection. Let's imagine that instead of logging the counter value, you update a field of your component and display it in its template. ``` constructor(appRef: ApplicationRef) { appRef.isStable.pipe( first(stable => stable), switchMap(() => interval(1000)) ).subscribe(counter => this.value = counter); } ``` As the `isStable` Observable runs outside the zone, the `value` field will be updated properly, but the template will not be refreshed! You'll have to manually trigger the change detection to update the template. ``` constructor(appRef: ApplicationRef, cd: ChangeDetectorRef) { appRef.isStable.pipe( first(stable => stable), switchMap(() => interval(1000)) ).subscribe(counter => { this.value = counter; cd.detectChanges(); }); } ``` Or make the subscription callback run inside the zone. ``` constructor(appRef: ApplicationRef, zone: NgZone) { appRef.isStable.pipe( first(stable => stable), switchMap(() => interval(1000)) ).subscribe(counter => zone.run(() => this.value = counter)); } ``` angular AfterContentChecked AfterContentChecked =================== `interface` A lifecycle hook that is called after the default change detector has completed checking all content of a directive. ``` interface AfterContentChecked { ngAfterContentChecked(): void } ``` See also -------- * `[AfterViewChecked](afterviewchecked)` * [Lifecycle hooks guide](../../guide/lifecycle-hooks) Methods ------- | ngAfterContentChecked() | | --- | | A callback method that is invoked immediately after the default change detector has completed checking all of the directive's content. | | `ngAfterContentChecked(): void` Parameters There are no parameters. Returns `void` | Usage notes ----------- The following snippet shows how a component can implement this interface to define its own after-check functionality. ``` @Component({selector: 'my-cmp', template: `...`}) class MyComponent implements AfterContentChecked { ngAfterContentChecked() { // ... } } ``` angular ForwardRefFn ForwardRefFn ============ `interface` An interface that a function passed into [`forwardRef`](forwardref) has to implement. ``` interface ForwardRefFn { (): any } ``` Methods ------- | *call signature* | | --- | | `(): any` Parameters There are no parameters. Returns `any` | Usage notes ----------- ### Example ``` const ref = forwardRef(() => Lock); ``` angular ProviderToken ProviderToken ============= `type-alias` Token that can be used to retrieve an instance from an injector or through a query. ``` type ProviderToken<T> = Type<T> | AbstractType<T> | InjectionToken<T>; ``` angular ImportedNgModuleProviders ImportedNgModuleProviders ========================= `type-alias` `deprecated` Providers that were imported from NgModules via the `[importProvidersFrom](importprovidersfrom)` function. [See more...](importedngmoduleproviders#description) **Deprecated:** replaced by `[EnvironmentProviders](environmentproviders)` ``` type ImportedNgModuleProviders = EnvironmentProviders; ``` See also -------- * `[importProvidersFrom](importprovidersfrom)` Description ----------- These providers are meant for use in an application injector (or other environment injectors) and should not be used in component injectors. This type cannot be directly implemented. It's returned from the `[importProvidersFrom](importprovidersfrom)` function and serves to prevent the extracted NgModule providers from being used in the wrong contexts.
programming_docs
angular Output Output ====== `decorator` Decorator that marks a class field as an output property and supplies configuration metadata. The DOM property bound to the output property is automatically updated during change detection. | Option | Description | | --- | --- | | [`bindingPropertyName?`](output#bindingPropertyName) | The name of the DOM property to which the output property is bound. | See also -------- * [Input and Output properties](../../guide/inputs-outputs) Options ------- | bindingPropertyName | | --- | | The name of the DOM property to which the output property is bound. | | `bindingPropertyName?: string` | | | Usage notes ----------- You can supply an optional name to use in templates when the component is instantiated, that maps to the name of the bound property. By default, the original name of the bound property is used for output binding. See `[Input](input)` decorator for an example of providing a binding name. angular ExistingSansProvider ExistingSansProvider ==================== `interface` Configures the `[Injector](injector)` to return a value of another `useExisting` token. ``` interface ExistingSansProvider { useExisting: any } ``` Child interfaces ---------------- * `[ExistingProvider](existingprovider)` See also -------- * `[ExistingProvider](existingprovider)` * ["Dependency Injection Guide"](../../guide/dependency-injection). Properties ---------- | Property | Description | | --- | --- | | `useExisting: any` | Existing `token` to return. (Equivalent to `injector.get(useExisting)`) | angular ErrorHandler ErrorHandler ============ `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Provides a hook for centralized exception handling. [See more...](errorhandler#description) ``` class ErrorHandler { handleError(error: any): void } ``` Description ----------- The default implementation of `[ErrorHandler](errorhandler)` prints error messages to the `console`. To intercept error handling, write a custom exception handler that replaces this default as appropriate for your app. Further information is available in the [Usage Notes...](errorhandler#usage-notes) Methods ------- | handleError() | | --- | | `handleError(error: any): void` Parameters | | | | | --- | --- | --- | | `error` | `any` | | Returns `void` | Usage notes ----------- ### Example ``` class MyErrorHandler implements ErrorHandler { handleError(error) { // do something with the exception } } @NgModule({ providers: [{provide: ErrorHandler, useClass: MyErrorHandler}] }) class MyModule {} ``` angular <ng-container> <ng-container> ============== `element` A special element that can hold structural directives without adding new elements to the DOM. [See more...](ng-container#description) Description ----------- The `[<ng-container>](ng-container)` allows us to use structural directives without any extra element, making sure that the only DOM changes being applied are those dictated by the directives themselves. This not only increases performance (even so slightly) since the browser ends up rendering less elements but can also be a valuable asset in having cleaner DOMs and styles alike. It can for example enable us to use structural directives without breaking styling dependent on a precise DOM structure (as for example the ones we get when using flex containers, margins, the child combinator selector, etc.). Further information is available in the [Usage Notes...](ng-container#usage-notes) Usage notes ----------- ### With `*[NgIf](../common/ngif)`s One common use case of `[<ng-container>](ng-container)` is alongside the `*[ngIf](../common/ngif)` structural directive. By using the special element we can produce very clean templates easy to understand and work with. For example, we may want to have a number of elements shown conditionally but they do not need to be all under the same root element. That can be easily done by wrapping them in such a block: ``` <ng-container *ngIf="condition"> … </ng-container> ``` This can also be augmented with an `else` statement alongside an `[<ng-template>](ng-template)` as: ``` <ng-container *ngIf="condition; else templateA"> … </ng-container> <ng-template #templateA> … </ng-template> ``` ### Combination of multiple structural directives Multiple structural directives cannot be used on the same element; if you need to take advantage of more than one structural directive, it is advised to use an `[<ng-container>](ng-container)` per structural directive. The most common scenario is with `*[ngIf](../common/ngif)` and `*[ngFor](../common/ngfor)`. For example, let's imagine that we have a list of items but each item needs to be displayed only if a certain condition is true. We could be tempted to try something like: ``` <ul> <li *ngFor="let item of items" *ngIf="item.isValid"> {{ item.name }} </li> </ul> ``` As we said that would not work, what we can do is to simply move one of the structural directives to an `[<ng-container>](ng-container)` element, which would then wrap the other one, like so: ``` <ul> <ng-container *ngFor="let item of items"> <li *ngIf="item.isValid"> {{ item.name }} </li> </ng-container> </ul> ``` This would work as intended without introducing any new unnecessary elements in the DOM. For more information see [one structural directive per element](../../guide/structural-directives#one-per-element). ### Use alongside ngTemplateOutlet The `[NgTemplateOutlet](../common/ngtemplateoutlet)` directive can be applied to any element but most of the time it's applied to `[<ng-container>](ng-container)` ones. By combining the two, we get a very clear and easy to follow HTML and DOM structure in which no extra elements are necessary and template views are instantiated where requested. For example, imagine a situation in which we have a large HTML, in which a small portion needs to be repeated in different places. A simple solution is to define an `[<ng-template>](ng-template)` containing our repeating HTML and render that where necessary by using `[<ng-container>](ng-container)` alongside an `[NgTemplateOutlet](../common/ngtemplateoutlet)`. Like so: ``` <!-- … --> <ng-container *ngTemplateOutlet="tmpl; context: {$implicit: 'Hello'}"> </ng-container> <!-- … --> <ng-container *ngTemplateOutlet="tmpl; context: {$implicit: 'World'}"> </ng-container> <!-- … --> <ng-template #tmpl let-text> <h1>{{ text }}</h1> </ng-template> ``` For more information regarding `[NgTemplateOutlet](../common/ngtemplateoutlet)`, see the [`NgTemplateOutlet`s api documentation page](../common/ngtemplateoutlet). angular StaticProvider StaticProvider ============== `type-alias` Describes how an `[Injector](injector)` should be configured as static (that is, without reflection). A static provider provides tokens to an injector for various types of dependencies. ``` type StaticProvider = ValueProvider | ExistingProvider | StaticClassProvider | ConstructorProvider | FactoryProvider | any[]; ``` See also -------- * `[Injector.create()](injector#create)`. * ["Dependency Injection Guide"](../../guide/dependency-injection-providers). angular reflectComponentType reflectComponentType ==================== `function` Creates an object that allows to retrieve component metadata. ### `reflectComponentType<C>(component: Type<C>): ComponentMirror<C> | null` ###### Parameters | | | | | --- | --- | --- | | `component` | `[Type](type)<C>` | Component class reference. | ###### Returns `[ComponentMirror](componentmirror)<C> | null`: An object that allows to retrieve component metadata. Usage notes ----------- The example below demonstrates how to use the function and how the fields of the returned object map to the component metadata. ``` @Component({ standalone: true, selector: 'foo-component', template: ` <ng-content></ng-content> <ng-content select="content-selector-a"></ng-content> `, }) class FooComponent { @Input('inputName') inputPropName: string; @Output('outputName') outputPropName = new EventEmitter<void>(); } const mirror = reflectComponentType(FooComponent); expect(mirror.type).toBe(FooComponent); expect(mirror.selector).toBe('foo-component'); expect(mirror.isStandalone).toBe(true); expect(mirror.inputs).toEqual([{propName: 'inputName', templateName: 'inputPropName'}]); expect(mirror.outputs).toEqual([{propName: 'outputName', templateName: 'outputPropName'}]); expect(mirror.ngContentSelectors).toEqual([ '*', // first `<ng-content>` in a template, the selector defaults to `*` 'content-selector-a' // second `<ng-content>` in a template ]); ``` angular Query Query ===== `class` Base class for query metadata. ``` abstract class Query { descendants: boolean emitDistinctChangesOnly: boolean first: boolean read: any isViewQuery: boolean selector: any static?: boolean } ``` See also -------- * `[ContentChildren](contentchildren)`. * `[ContentChild](contentchild)`. * `[ViewChildren](viewchildren)`. * `[ViewChild](viewchild)`. Properties ---------- | Property | Description | | --- | --- | | `descendants: boolean` | | | `emitDistinctChangesOnly: boolean` | | | `first: boolean` | | | `read: any` | | | `isViewQuery: boolean` | | | `selector: any` | | | `[static](../upgrade/static)?: boolean` | | angular StaticClassProvider StaticClassProvider =================== `interface` Configures the `[Injector](injector)` to return an instance of `useClass` for a token. ``` interface StaticClassProvider extends StaticClassSansProvider { provide: any multi?: boolean // inherited from core/StaticClassSansProvider useClass: Type<any> deps: any[] } ``` See also -------- * ["Dependency Injection Guide"](../../guide/dependency-injection). Properties ---------- | Property | Description | | --- | --- | | `provide: any` | An injection token. Typically an instance of `[Type](type)` or `[InjectionToken](injectiontoken)`, but can be `any`. | | `multi?: boolean` | When true, injector returns an array of instances. This is useful to allow multiple providers spread across many files to provide configuration information to a common token. | Usage notes ----------- ``` abstract class Shape { name!: string; } class Square extends Shape { override name = 'square'; } const injector = Injector.create({providers: [{provide: Shape, useClass: Square, deps: []}]}); const shape: Shape = injector.get(Shape); expect(shape.name).toEqual('square'); expect(shape instanceof Square).toBe(true); ``` Note that following two providers are not equal: ``` class Greeting { salutation = 'Hello'; } class FormalGreeting extends Greeting { override salutation = 'Greetings'; } const injector = Injector.create({ providers: [ {provide: FormalGreeting, useClass: FormalGreeting, deps: []}, {provide: Greeting, useClass: FormalGreeting, deps: []} ] }); // The injector returns different instances. // See: {provide: ?, useExisting: ?} if you want the same instance. expect(injector.get(FormalGreeting)).not.toBe(injector.get(Greeting)); ``` ### Multi-value example ``` const locale = new InjectionToken<string[]>('locale'); const injector = Injector.create({ providers: [ {provide: locale, multi: true, useValue: 'en'}, {provide: locale, multi: true, useValue: 'sk'}, ] }); const locales: string[] = injector.get(locale); expect(locales).toEqual(['en', 'sk']); ``` angular ViewEncapsulation ViewEncapsulation ================= `enum` Defines the CSS styles encapsulation policies for the [`Component`](component) decorator's `encapsulation` option. [See more...](viewencapsulation#description) ``` enum ViewEncapsulation { Emulated: 0 None: 2 ShadowDom: 3 } ``` Description ----------- See [encapsulation](component#encapsulation). Further information is available in the [Usage Notes...](viewencapsulation#usage-notes) Members ------- | Member | Description | | --- | --- | | `Emulated: 0` | Emulates a native Shadow DOM encapsulation behavior by adding a specific attribute to the component's host element and applying the same attribute to all the CSS selectors provided via [styles](component#styles) or [styleUrls](component#styleUrls). This is the default option. | | `None: 2` | Doesn't provide any sort of CSS style encapsulation, meaning that all the styles provided via [styles](component#styles) or [styleUrls](component#styleUrls) are applicable to any HTML element of the application regardless of their host Component. | | `ShadowDom: 3` | Uses the browser's native Shadow DOM API to encapsulate CSS styles, meaning that it creates a ShadowRoot for the component's host element which is then used to encapsulate all the Component's styling. | Usage notes ----------- ### Example ``` @Component({ selector: 'app-root', template: ` <h1>Hello World!</h1> <span class="red">Shadow DOM Rocks!</span> `, styles: [` :host { display: block; border: 1px solid black; } h1 { color: blue; } .red { background-color: red; } `], encapsulation: ViewEncapsulation.ShadowDom }) class MyApp { } ``` angular Input Input ===== `decorator` Decorator that marks a class field as an input property and supplies configuration metadata. The input property is bound to a DOM property in the template. During change detection, Angular automatically updates the data property with the DOM property's value. | Option | Description | | --- | --- | | [`bindingPropertyName?`](input#bindingPropertyName) | The name of the DOM property to which the input property is bound. | See also -------- * [Input and Output properties](../../guide/inputs-outputs) Options ------- | bindingPropertyName | | --- | | The name of the DOM property to which the input property is bound. | | `bindingPropertyName?: string` | | | Usage notes ----------- You can supply an optional name to use in templates when the component is instantiated, that maps to the name of the bound property. By default, the original name of the bound property is used for input binding. The following example creates a component with two input properties, one of which is given a special binding name. ``` @Component({ selector: 'bank-account', template: ` Bank Name: {{bankName}} Account Id: {{id}} ` }) class BankAccount { // This property is bound using its original name. @Input() bankName: string; // this property value is bound to a different property name // when this component is instantiated in a template. @Input('account-id') id: string; // this property is not bound, and is not automatically updated by Angular normalizedBankName: string; } @Component({ selector: 'app', template: ` <bank-account bankName="RBC" account-id="4747"></bank-account> ` }) class App {} ``` angular TypeProvider TypeProvider ============ `interface` Configures the `[Injector](injector)` to return an instance of `[Type](type)` when `Type' is used as the token. [See more...](typeprovider#description) ``` interface TypeProvider extends Type<any> { // inherited from core/Type constructor(...args: any[]): T } ``` Description ----------- Create an instance by invoking the `new` operator and supplying additional arguments. This form is a short form of `[TypeProvider](typeprovider)`; For more details, see the ["Dependency Injection Guide"](../../guide/dependency-injection). Further information is available in the [Usage Notes...](typeprovider#usage-notes) Usage notes ----------- ``` @Injectable() class Greeting { salutation = 'Hello'; } const injector = ReflectiveInjector.resolveAndCreate([ Greeting, // Shorthand for { provide: Greeting, useClass: Greeting } ]); expect(injector.get(Greeting).salutation).toBe('Hello'); ``` angular createComponent createComponent =============== `function` Creates a `[ComponentRef](componentref)` instance based on provided component type and a set of options. ### `createComponent<C>(component: Type<C>, options: { environmentInjector: EnvironmentInjector; hostElement?: Element; elementInjector?: Injector; projectableNodes?: Node[][]; }): ComponentRef<C>` ###### Parameters | | | | | --- | --- | --- | | `component` | `[Type](type)<C>` | Component class reference. | | `options` | `object` | Set of options to use:* `environmentInjector`: An `[EnvironmentInjector](environmentinjector)` instance to be used for the component, see additional info about it at [https://angular.io/guide/standalone-components#environment-injectors](../../guide/standalone-components#environment-injectors). * `hostElement` (optional): A DOM node that should act as a host node for the component. If not provided, Angular creates one based on the tag name used in the component selector (and falls back to using `div` if selector doesn't have tag name info). * `elementInjector` (optional): An `ElementInjector` instance, see additional info about it at [https://angular.io/guide/hierarchical-dependency-injection#elementinjector](../../guide/hierarchical-dependency-injection#elementinjector). * `projectableNodes` (optional): A list of DOM nodes that should be projected through [`<ng-content>`](ng-content) of the new component instance. | ###### Returns `[ComponentRef<C>](componentref)`: ComponentRef instance that represents a given Component. Usage notes ----------- The example below demonstrates how the `[createComponent](createcomponent)` function can be used to create an instance of a ComponentRef dynamically and attach it to an ApplicationRef, so that it gets included into change detection cycles. Note: the example uses standalone components, but the function can also be used for non-standalone components (declared in an NgModule) as well. ``` @Component({ standalone: true, template: `Hello {{ name }}!` }) class HelloComponent { name = 'Angular'; } @Component({ standalone: true, template: `<div id="hello-component-host"></div>` }) class RootComponent {} // Bootstrap an application. const applicationRef = await bootstrapApplication(RootComponent); // Locate a DOM node that would be used as a host. const host = document.getElementById('hello-component-host'); // Get an `EnvironmentInjector` instance from the `ApplicationRef`. const environmentInjector = applicationRef.injector; // We can now create a `ComponentRef` instance. const componentRef = createComponent(HelloComponent, {host, environmentInjector}); // Last step is to register the newly created ref using the `ApplicationRef` instance // to include the component view into change detection cycles. applicationRef.attachView(componentRef.hostView); ``` angular createNgModule createNgModule ============== `function` Returns a new NgModuleRef instance based on the NgModule class and parent injector provided. ### `createNgModule<T>(ngModule: Type<T>, parentInjector?: Injector): viewEngine_NgModuleRef<T>` ###### Parameters | | | | | --- | --- | --- | | `ngModule` | `[Type<T>](type)` | NgModule class. | | `parentInjector` | `[Injector](injector)` | Optional injector instance to use as a parent for the module injector. If not provided, `NullInjector` will be used instead. Optional. Default is `undefined`. | ###### Returns `viewEngine_NgModuleRef<T>`: NgModuleRef that represents an NgModule instance. angular RendererFactory2 RendererFactory2 ================ `class` Creates and initializes a custom renderer that implements the `[Renderer2](renderer2)` base class. ``` abstract class RendererFactory2 { abstract createRenderer(hostElement: any, type: RendererType2): Renderer2 abstract begin()?: void abstract end()?: void abstract whenRenderingDone()?: Promise<any> } ``` Methods ------- | createRenderer() | | --- | | Creates and initializes a custom renderer for a host DOM element. | | `abstract createRenderer(hostElement: any, type: RendererType2): Renderer2` Parameters | | | | | --- | --- | --- | | `hostElement` | `any` | The element to render. | | `type` | `[RendererType2](renderertype2)` | The base class to implement. | Returns `[Renderer2](renderer2)`: The new custom renderer instance. | | begin() | | --- | | A callback invoked when rendering has begun. | | `abstract begin()?: void` Parameters There are no parameters. Returns `void` | | end() | | --- | | A callback invoked when rendering has completed. | | `abstract end()?: void` Parameters There are no parameters. Returns `void` | | whenRenderingDone() | | --- | | Use with animations test-only mode. Notifies the test when rendering has completed. | | `abstract whenRenderingDone()?: Promise<any>` Parameters There are no parameters. Returns `Promise<any>`: The asynchronous result of the developer-defined function. |
programming_docs
angular ResolvedReflectiveProvider ResolvedReflectiveProvider ========================== `interface` An internal resolved representation of a `[Provider](provider)` used by the `[Injector](injector)`. ``` interface ResolvedReflectiveProvider { key: ReflectiveKey resolvedFactories: ResolvedReflectiveFactory[] multiProvider: boolean } ``` Properties ---------- | Property | Description | | --- | --- | | `key: [ReflectiveKey](reflectivekey)` | A key, usually a `[Type](type)<any>`. | | `resolvedFactories: [ResolvedReflectiveFactory](resolvedreflectivefactory)[]` | Factory function which can return an instance of an object represented by a key. | | `multiProvider: boolean` | Indicates if the provider is a multi-provider or a regular provider. | Usage notes ----------- This is usually created automatically by `Injector.resolveAndCreate`. It can be created manually, as follows: ### Example ``` var resolvedProviders = Injector.resolve([{ provide: 'message', useValue: 'Hello' }]); var injector = Injector.fromResolvedProviders(resolvedProviders); expect(injector.get('message')).toEqual('Hello'); ``` angular KeyValueChanges KeyValueChanges =============== `interface` An object describing the changes in the `Map` or `{[k:string]: string}` since last time `[KeyValueDiffer](keyvaluediffer)#diff()` was invoked. ``` interface KeyValueChanges<K, V> { forEachItem(fn: (r: KeyValueChangeRecord<K, V>) => void): void forEachPreviousItem(fn: (r: KeyValueChangeRecord<K, V>) => void): void forEachChangedItem(fn: (r: KeyValueChangeRecord<K, V>) => void): void forEachAddedItem(fn: (r: KeyValueChangeRecord<K, V>) => void): void forEachRemovedItem(fn: (r: KeyValueChangeRecord<K, V>) => void): void } ``` Methods ------- | forEachItem() | | --- | | Iterate over all changes. `[KeyValueChangeRecord](keyvaluechangerecord)` will contain information about changes to each item. | | `forEachItem(fn: (r: KeyValueChangeRecord<K, V>) => void): void` Parameters | | | | | --- | --- | --- | | `fn` | `(r: [KeyValueChangeRecord](keyvaluechangerecord)<K, V>) => void` | | Returns `void` | | forEachPreviousItem() | | --- | | Iterate over changes in the order of original Map showing where the original items have moved. | | `forEachPreviousItem(fn: (r: KeyValueChangeRecord<K, V>) => void): void` Parameters | | | | | --- | --- | --- | | `fn` | `(r: [KeyValueChangeRecord](keyvaluechangerecord)<K, V>) => void` | | Returns `void` | | forEachChangedItem() | | --- | | Iterate over all keys for which values have changed. | | `forEachChangedItem(fn: (r: KeyValueChangeRecord<K, V>) => void): void` Parameters | | | | | --- | --- | --- | | `fn` | `(r: [KeyValueChangeRecord](keyvaluechangerecord)<K, V>) => void` | | Returns `void` | | forEachAddedItem() | | --- | | Iterate over all added items. | | `forEachAddedItem(fn: (r: KeyValueChangeRecord<K, V>) => void): void` Parameters | | | | | --- | --- | --- | | `fn` | `(r: [KeyValueChangeRecord](keyvaluechangerecord)<K, V>) => void` | | Returns `void` | | forEachRemovedItem() | | --- | | Iterate over all removed items. | | `forEachRemovedItem(fn: (r: KeyValueChangeRecord<K, V>) => void): void` Parameters | | | | | --- | --- | --- | | `fn` | `(r: [KeyValueChangeRecord](keyvaluechangerecord)<K, V>) => void` | | Returns `void` | angular NgModuleFactory NgModuleFactory =============== `class` `deprecated` **Deprecated:** This class was mostly used as a part of ViewEngine-based JIT API and is no longer needed in Ivy JIT mode. See [JIT API changes due to ViewEngine deprecation](../../guide/deprecations#jit-api-changes) for additional context. Angular provides APIs that accept NgModule classes directly (such as [PlatformRef.bootstrapModule](platformref#bootstrapModule) and [createNgModule](createngmodule)), consider switching to those APIs instead of using factory-based ones. ``` abstract class NgModuleFactory<T> { abstract moduleType: Type<T> abstract create(parentInjector: Injector): NgModuleRef<T> } ``` Properties ---------- | Property | Description | | --- | --- | | `abstract moduleType: [Type](type)<T>` | Read-Only | Methods ------- | create() | | --- | | `abstract create(parentInjector: Injector): NgModuleRef<T>` Parameters | | | | | --- | --- | --- | | `parentInjector` | `[Injector](injector)` | | Returns `[NgModuleRef<T>](ngmoduleref)` | angular TrackByFunction TrackByFunction =============== `interface` A function optionally passed into the `[NgForOf](../common/ngforof)` directive to customize how `[NgForOf](../common/ngforof)` uniquely identifies items in an iterable. [See more...](trackbyfunction#description) ``` interface TrackByFunction<T> { <U extends T>(index: number, item: T & U): any } ``` See also -------- * [`NgForOf#ngForTrackBy`](../common/ngforof#ngForTrackBy) Description ----------- `[NgForOf](../common/ngforof)` needs to uniquely identify items in the iterable to correctly perform DOM updates when items in the iterable are reordered, new items are added, or existing items are removed. In all of these scenarios it is usually desirable to only update the DOM elements associated with the items affected by the change. This behavior is important to: * preserve any DOM-specific UI state (like cursor position, focus, text selection) when the iterable is modified * enable animation of item addition, removal, and iterable reordering * preserve the value of the `<select>` element when nested `<option>` elements are dynamically populated using `[NgForOf](../common/ngforof)` and the bound iterable is updated A common use for custom `trackBy` functions is when the model that `[NgForOf](../common/ngforof)` iterates over contains a property with a unique identifier. For example, given a model: ``` class User { id: number; name: string; ... } ``` a custom `trackBy` function could look like the following: ``` function userTrackBy(index, user) { return user.id; } ``` A custom `trackBy` function must have several properties: * be [idempotent](https://en.wikipedia.org/wiki/Idempotence) (be without side effects, and always return the same value for a given input) * return unique value for all unique inputs * be fast Methods ------- | *call signature* | | --- | | `<U extends T>(index: number, item: T & U): any` Parameters | | | | | --- | --- | --- | | `index` | `number` | The index of the item within the iterable. | | `item` | `T & U` | The item in the iterable. | Returns `any` | angular BootstrapOptions BootstrapOptions ================ `interface` Provides additional options to the bootstrapping process. ``` interface BootstrapOptions { ngZone?: NgZone | 'zone.js' | 'noop' ngZoneEventCoalescing?: boolean ngZoneRunCoalescing?: boolean } ``` Properties ---------- | Property | Description | | --- | --- | | `ngZone?: [NgZone](ngzone) | 'zone.js' | 'noop'` | Optionally specify which `[NgZone](ngzone)` should be used.* Provide your own `[NgZone](ngzone)` instance. * `zone.js` - Use default `[NgZone](ngzone)` which requires `Zone.js`. * `noop` - Use `NoopNgZone` which does nothing. | | `ngZoneEventCoalescing?: boolean` | Optionally specify coalescing event change detections or not. Consider the following case. ``` <div (click)="doSomething()"> <button (click)="doSomethingElse()"></button> </div> ``` When button is clicked, because of the event bubbling, both event handlers will be called and 2 change detections will be triggered. We can coalesce such kind of events to only trigger change detection only once. By default, this option will be false. So the events will not be coalesced and the change detection will be triggered multiple times. And if this option be set to true, the change detection will be triggered async by scheduling a animation frame. So in the case above, the change detection will only be triggered once. | | `ngZoneRunCoalescing?: boolean` | Optionally specify if `[NgZone](ngzone)#run()` method invocations should be coalesced into a single change detection. Consider the following case. ``` for (let i = 0; i < 10; i ++) { ngZone.run(() => { // do something }); } ``` This case triggers the change detection multiple times. With ngZoneRunCoalescing options, all change detections in an event loop trigger only once. In addition, the change detection executes in requestAnimation. | angular ExistingProvider ExistingProvider ================ `interface` Configures the `[Injector](injector)` to return a value of another `useExisting` token. ``` interface ExistingProvider extends ExistingSansProvider { provide: any multi?: boolean // inherited from core/ExistingSansProvider useExisting: any } ``` See also -------- * ["Dependency Injection Guide"](../../guide/dependency-injection). Properties ---------- | Property | Description | | --- | --- | | `provide: any` | An injection token. Typically an instance of `[Type](type)` or `[InjectionToken](injectiontoken)`, but can be `any`. | | `multi?: boolean` | When true, injector returns an array of instances. This is useful to allow multiple providers spread across many files to provide configuration information to a common token. | Usage notes ----------- ``` class Greeting { salutation = 'Hello'; } class FormalGreeting extends Greeting { override salutation = 'Greetings'; } const injector = Injector.create({ providers: [ {provide: FormalGreeting, deps: []}, {provide: Greeting, useExisting: FormalGreeting} ] }); expect(injector.get(Greeting).salutation).toEqual('Greetings'); expect(injector.get(FormalGreeting).salutation).toEqual('Greetings'); expect(injector.get(FormalGreeting)).toBe(injector.get(Greeting)); ``` ### Multi-value example ``` const locale = new InjectionToken<string[]>('locale'); const injector = Injector.create({ providers: [ {provide: locale, multi: true, useValue: 'en'}, {provide: locale, multi: true, useValue: 'sk'}, ] }); const locales: string[] = injector.get(locale); expect(locales).toEqual(['en', 'sk']); ``` angular Attribute Attribute ========= `decorator` Parameter decorator for a directive constructor that designates a host-element attribute whose value is injected as a constant string literal. | Option | Description | | --- | --- | | [`attributeName`](attribute#attributeName) | The name of the attribute whose value can be injected. | Options ------- | attributeName | | --- | | The name of the attribute whose value can be injected. | | `attributeName: string` | | | Usage notes ----------- Suppose we have an `<input>` element and want to know its `type`. ``` <input type="text"> ``` The following example uses the decorator to inject the string literal `text` in a directive. ``` @Directive({selector: 'input'}) class InputAttrDirective { constructor(@Attribute('type') type: string) { // type would be 'text' in this example } } ``` The following example uses the decorator in a component constructor. ``` @Component({selector: 'page', template: 'Title: {{title}}'}) class Page { title: string; constructor(@Attribute('title') title: string) { this.title = title; } } ``` angular AfterContentInit AfterContentInit ================ `interface` A lifecycle hook that is called after Angular has fully initialized all content of a directive. Define an `ngAfterContentInit()` method to handle any additional initialization tasks. ``` interface AfterContentInit { ngAfterContentInit(): void } ``` Class implementations --------------------- * `[RouterLinkActive](../router/routerlinkactive)` See also -------- * `[OnInit](oninit)` * `[AfterViewInit](afterviewinit)` * [Lifecycle hooks guide](../../guide/lifecycle-hooks) Methods ------- | ngAfterContentInit() | | --- | | A callback method that is invoked immediately after Angular has completed initialization of all of the directive's content. It is invoked only once when the directive is instantiated. | | `ngAfterContentInit(): void` Parameters There are no parameters. Returns `void` | Usage notes ----------- The following snippet shows how a component can implement this interface to define its own content initialization method. ``` @Component({selector: 'my-cmp', template: `...`}) class MyComponent implements AfterContentInit { ngAfterContentInit() { // ... } } ``` angular SimpleChange SimpleChange ============ `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Represents a basic change from a previous to a new value for a single property on a directive instance. Passed as a value in a [`SimpleChanges`](simplechanges) object to the `ngOnChanges` hook. ``` class SimpleChange { constructor(previousValue: any, currentValue: any, firstChange: boolean) previousValue: any currentValue: any firstChange: boolean isFirstChange(): boolean } ``` See also -------- * `[OnChanges](onchanges)` Constructor ----------- | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `constructor(previousValue: any, currentValue: any, firstChange: boolean)` Parameters | | | | | --- | --- | --- | | `previousValue` | `any` | | | `currentValue` | `any` | | | `firstChange` | `boolean` | | | Properties ---------- | Property | Description | | --- | --- | | `previousValue: any` | Declared in Constructor | | `currentValue: any` | Declared in Constructor | | `firstChange: boolean` | Declared in Constructor | Methods ------- | isFirstChange() | | --- | | Check whether the new value is the first value assigned. | | `isFirstChange(): boolean` Parameters There are no parameters. Returns `boolean` | angular createEnvironmentInjector createEnvironmentInjector ========================= `function` Create a new environment injector. [See more...](createenvironmentinjector#description) ### `createEnvironmentInjector(providers: (Provider | EnvironmentProviders)[], parent: EnvironmentInjector, debugName: string = null): EnvironmentInjector` ###### Parameters | | | | | --- | --- | --- | | `providers` | `([Provider](provider) | [EnvironmentProviders](environmentproviders))[]` | An array of providers. | | `parent` | `[EnvironmentInjector](environmentinjector)` | A parent environment injector. | | `debugName` | `string` | An optional name for this injector instance, which will be used in error messages. Optional. Default is `null`. | ###### Returns `[EnvironmentInjector](environmentinjector)` Description ----------- Learn more about environment injectors in [this guide](../../guide/standalone-components#environment-injectors). angular ContentChild ContentChild ============ `decorator` Property decorator that configures a content query. [See more...](contentchild#description) Description ----------- Use to get the first element or the directive matching the selector from the content DOM. If the content DOM changes, and a new child matches the selector, the property will be updated. Content queries are set before the `ngAfterContentInit` callback is called. Does not retrieve elements or directives that are in other components' templates, since a component's template is always a black box to its ancestors. **Metadata Properties**: * **selector** - The directive type or the name used for querying. * **descendants** - If `true` (default) include all descendants of the element. If `false` then only query direct children of the element. * **read** - Used to read a different token from the queried element. * **static** - True to resolve query results before change detection runs, false to resolve after change detection. Defaults to false. The following selectors are supported. * Any class with the `@[Component](component)` or `@[Directive](directive)` decorator * A template reference variable as a string (e.g. query `<my-component #cmp></my-component>` with `@[ContentChild](contentchild)('cmp')`) * Any provider defined in the child component tree of the current component (e.g. `@[ContentChild](contentchild)(SomeService) someService: SomeService`) * Any provider defined through a string token (e.g. `@[ContentChild](contentchild)('someToken') someTokenVal: any`) * A `[TemplateRef](templateref)` (e.g. query `<ng-template></ng-template>` with `@[ContentChild](contentchild)([TemplateRef](templateref)) template;`) The following values are supported by `read`: * Any class with the `@[Component](component)` or `@[Directive](directive)` decorator * Any provider defined on the injector of the component that is matched by the `selector` of this query * Any provider defined through a string token (e.g. `{provide: 'token', useValue: 'val'}`) * `[TemplateRef](templateref)`, `[ElementRef](elementref)`, and `[ViewContainerRef](viewcontainerref)` Further information is available in the [Usage Notes...](contentchild#usage-notes) Options ------- Usage notes ----------- ``` import {AfterContentInit, ContentChild, Directive} from '@angular/core'; @Directive({selector: 'child-directive'}) class ChildDirective { } @Directive({selector: 'someDir'}) class SomeDir implements AfterContentInit { @ContentChild(ChildDirective) contentChild!: ChildDirective; ngAfterContentInit() { // contentChild is set } } ``` ### Example ``` import {Component, ContentChild, Directive, Input} from '@angular/core'; @Directive({selector: 'pane'}) export class Pane { @Input() id!: string; } @Component({ selector: 'tab', template: ` <div>pane: {{pane?.id}}</div> ` }) export class Tab { @ContentChild(Pane) pane!: Pane; } @Component({ selector: 'example-app', template: ` <tab> <pane id="1" *ngIf="shouldShow"></pane> <pane id="2" *ngIf="!shouldShow"></pane> </tab> <button (click)="toggle()">Toggle</button> `, }) export class ContentChildComp { shouldShow = true; toggle() { this.shouldShow = !this.shouldShow; } } ``` angular createPlatform createPlatform ============== `function` Creates a platform. Platforms must be created on launch using this function. ### `createPlatform(injector: Injector): PlatformRef` ###### Parameters | | | | | --- | --- | --- | | `injector` | `[Injector](injector)` | | ###### Returns `[PlatformRef](platformref)` angular createNgModuleRef createNgModuleRef ================= `const` `deprecated` The `[createNgModule](createngmodule)` function alias for backwards-compatibility. Please avoid using it directly and use `[createNgModule](createngmodule)` instead. **Deprecated:** Use `[createNgModule](createngmodule)` instead. ### `const createNgModuleRef: <T>(ngModule: Type<T>, parentInjector?: Injector) => NgModuleRef<T>;` angular getModuleFactory getModuleFactory ================ `function` `deprecated` Returns the NgModuleFactory with the given id (specified using [@NgModule.id field](ngmodule#id)), if it exists and has been loaded. Factories for NgModules that do not specify an `id` cannot be retrieved. Throws if an NgModule cannot be found. **Deprecated:** Use `[getNgModuleById](getngmodulebyid)` instead. ### `getModuleFactory(id: string): NgModuleFactory<any>` **Deprecated** Use `[getNgModuleById](getngmodulebyid)` instead. ###### Parameters | | | | | --- | --- | --- | | `id` | `string` | | ###### Returns `[NgModuleFactory](ngmodulefactory)<any>` angular ImportProvidersSource ImportProvidersSource ===================== `type-alias` A source of providers for the `[importProvidersFrom](importprovidersfrom)` function. ``` type ImportProvidersSource = Type<unknown> | ModuleWithProviders<unknown> | Array<ImportProvidersSource>; ``` angular Sanitizer Sanitizer ========= `class` Sanitizer is used by the views to sanitize potentially dangerous values. ``` abstract class Sanitizer { abstract sanitize(context: SecurityContext, value: string | {}): string | null } ``` Subclasses ---------- * `[DomSanitizer](../platform-browser/domsanitizer)` Provided in ----------- * ``` 'root' ``` Methods ------- | sanitize() | | --- | | `abstract sanitize(context: SecurityContext, value: string | {}): string | null` Parameters | | | | | --- | --- | --- | | `context` | `[SecurityContext](securitycontext)` | | | `value` | `string | {}` | | Returns `string | null` |
programming_docs
angular InjectOptions InjectOptions ============= `interface` Type of the options argument to `inject`. ``` interface InjectOptions { optional?: boolean skipSelf?: boolean self?: boolean host?: boolean } ``` Properties ---------- | Property | Description | | --- | --- | | `optional?: boolean` | Use optional injection, and return `null` if the requested token is not found. | | `skipSelf?: boolean` | Start injection at the parent of the current injector. | | `self?: boolean` | Only query the current injector for the token, and don't fall back to the parent injector if it's not found. | | `host?: boolean` | Stop injection at the host component's injector. Only relevant when injecting from an element injector, and a no-op for environment injectors. | angular InjectableProvider InjectableProvider ================== `type-alias` Injectable providers used in `@[Injectable](injectable)` decorator. ``` type InjectableProvider = ValueSansProvider | ExistingSansProvider | StaticClassSansProvider | ConstructorSansProvider | FactorySansProvider | ClassSansProvider; ``` angular TestabilityRegistry TestabilityRegistry =================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A global registry of [`Testability`](testability) instances for specific elements. ``` class TestabilityRegistry { registerApplication(token: any, testability: Testability) unregisterApplication(token: any) unregisterAllApplications() getTestability(elem: any): Testability | null getAllTestabilities(): Testability[] getAllRootElements(): any[] findTestabilityInTree(elem: Node, findInAncestors: boolean = true): Testability | null } ``` Provided in ----------- * ``` 'platform' ``` Methods ------- | registerApplication() | | --- | | Registers an application with a testability hook so that it can be tracked | | `registerApplication(token: any, testability: Testability)` Parameters | | | | | --- | --- | --- | | `token` | `any` | token of application, root element | | `testability` | `[Testability](testability)` | Testability hook | | | unregisterApplication() | | --- | | Unregisters an application. | | `unregisterApplication(token: any)` Parameters | | | | | --- | --- | --- | | `token` | `any` | token of application, root element | | | unregisterAllApplications() | | --- | | Unregisters all applications | | `unregisterAllApplications()` Parameters There are no parameters. | | getTestability() | | --- | | Get a testability hook associated with the application | | `getTestability(elem: any): Testability | null` Parameters | | | | | --- | --- | --- | | `elem` | `any` | root element | Returns `[Testability](testability) | null` | | getAllTestabilities() | | --- | | Get all registered testabilities | | `getAllTestabilities(): Testability[]` Parameters There are no parameters. Returns `[Testability](testability)[]` | | getAllRootElements() | | --- | | Get all registered applications(root elements) | | `getAllRootElements(): any[]` Parameters There are no parameters. Returns `any[]` | | findTestabilityInTree() | | --- | | Find testability of a node in the Tree | | `findTestabilityInTree(elem: Node, findInAncestors: boolean = true): Testability | null` Parameters | | | | | --- | --- | --- | | `elem` | `Node` | node | | `findInAncestors` | `boolean` | whether finding testability in ancestors if testability was not found in current node Optional. Default is `true`. | Returns `[Testability](testability) | null` | angular TemplateRef TemplateRef =========== `class` Represents an embedded template that can be used to instantiate embedded views. To instantiate embedded views based on a template, use the `[ViewContainerRef](viewcontainerref)` method `createEmbeddedView()`. [See more...](templateref#description) ``` abstract class TemplateRef<C> { abstract elementRef: ElementRef abstract createEmbeddedView(context: C, injector?: Injector): EmbeddedViewRef<C> } ``` See also -------- * `[ViewContainerRef](viewcontainerref)` * [Navigate the Component Tree with DI](../../guide/dependency-injection-navtree) Description ----------- Access a `[TemplateRef](templateref)` instance by placing a directive on an `[<ng-template>](ng-template)` element (or directive prefixed with `*`). The `[TemplateRef](templateref)` for the embedded view is injected into the constructor of the directive, using the `[TemplateRef](templateref)` token. You can also use a `[Query](query)` to find a `[TemplateRef](templateref)` associated with a component or a directive. Properties ---------- | Property | Description | | --- | --- | | `abstract elementRef: [ElementRef](elementref)` | Read-Only The anchor element in the parent view for this embedded view. The data-binding and injection contexts of embedded views created from this `[TemplateRef](templateref)` inherit from the contexts of this location. Typically new embedded views are attached to the view container of this location, but in advanced use-cases, the view can be attached to a different container while keeping the data-binding and injection context from the original location. | Methods ------- | createEmbeddedView() | | --- | | Instantiates an unattached embedded view based on this template. | | `abstract createEmbeddedView(context: C, injector?: Injector): EmbeddedViewRef<C>` Parameters | | | | | --- | --- | --- | | `context` | `C` | The data-binding context of the embedded view, as declared in the `[<ng-template>](ng-template)` usage. | | `injector` | `[Injector](injector)` | Injector to be used within the embedded view. Optional. Default is `undefined`. | Returns `[EmbeddedViewRef<C>](embeddedviewref)`: The new embedded view object. | angular Host Host ==== `decorator` Parameter decorator on a view-provider parameter of a class constructor that tells the DI framework to resolve the view by checking injectors of child elements, and stop when reaching the host element of the current component. Options ------- Usage notes ----------- The following shows use with the `@[Optional](optional)` decorator, and allows for a `null` result. ``` class OtherService {} class HostService {} @Directive({selector: 'child-directive'}) class ChildDirective { logs: string[] = []; constructor(@Optional() @Host() os: OtherService, @Optional() @Host() hs: HostService) { // os is null: true this.logs.push(`os is null: ${os === null}`); // hs is an instance of HostService: true this.logs.push(`hs is an instance of HostService: ${hs instanceof HostService}`); } } @Component({ selector: 'parent-cmp', viewProviders: [HostService], template: '<child-directive></child-directive>', }) class ParentCmp { } @Component({ selector: 'app', viewProviders: [OtherService], template: '<parent-cmp></parent-cmp>', }) class App { } ``` For an extended example, see ["Dependency Injection Guide"](../../guide/dependency-injection-in-action#optional). angular TRANSLATIONS TRANSLATIONS ============ `const` Use this token at bootstrap to provide the content of your translation file (`xtb`, `xlf` or `xlf2`) when you want to translate your application in another language. [See more...](translations#description) ### `const TRANSLATIONS: InjectionToken<string>;` #### Description See the [i18n guide](../../guide/i18n-common-merge) for more information. Further information is available in the [Usage Notes...](translations#usage-notes) Usage notes ----------- #### Example ``` import { TRANSLATIONS } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; // content of your translation file const translations = '....'; platformBrowserDynamic().bootstrapModule(AppModule, { providers: [{provide: TRANSLATIONS, useValue: translations }] }); ``` angular ModuleWithComponentFactories ModuleWithComponentFactories ============================ `class` `deprecated` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Combination of NgModuleFactory and ComponentFactories. **Deprecated:** Ivy JIT mode doesn't require accessing this symbol. See [JIT API changes due to ViewEngine deprecation](../../guide/deprecations#jit-api-changes) for additional context. ``` class ModuleWithComponentFactories<T> { constructor(ngModuleFactory: NgModuleFactory<T>, componentFactories: ComponentFactory<any>[]) ngModuleFactory: NgModuleFactory<T> componentFactories: ComponentFactory<any>[] } ``` Constructor ----------- | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | | `constructor(ngModuleFactory: NgModuleFactory<T>, componentFactories: ComponentFactory<any>[])` Parameters | | | | | --- | --- | --- | | `ngModuleFactory` | `[NgModuleFactory<T>](ngmodulefactory)` | | | `componentFactories` | `[ComponentFactory](componentfactory)<any>[]` | | | Properties ---------- | Property | Description | | --- | --- | | `ngModuleFactory: [NgModuleFactory](ngmodulefactory)<T>` | Declared in Constructor | | `componentFactories: [ComponentFactory](componentfactory)<any>[]` | Declared in Constructor | angular APP_BOOTSTRAP_LISTENER APP\_BOOTSTRAP\_LISTENER ======================== `const` A [DI token](../../guide/glossary#di-token "DI token definition") that provides a set of callbacks to be called for every component that is bootstrapped. [See more...](app_bootstrap_listener#description) ### `const APP_BOOTSTRAP_LISTENER: InjectionToken<((compRef: ComponentRef<any>) => void)[]>;` #### Description Each callback must take a `[ComponentRef](componentref)` instance and return nothing. `(componentRef: [ComponentRef](componentref)) => void` angular @angular/core/testing @angular/core/testing ===================== `entry-point` Provides infrastructure for testing Angular core functionality. Entry point exports ------------------- ### Classes | | | | --- | --- | | `[ComponentFixture](testing/componentfixture)` | Fixture for debugging and testing a component. | | `[InjectSetupWrapper](testing/injectsetupwrapper)` | | | `[TestBed](testing/testbed)` | Configures and initializes environment for unit testing and provides methods for creating components and services in unit tests. | | `[TestComponentRenderer](testing/testcomponentrenderer)` | An abstract class for inserting the root test component element in a platform independent way. | ### Functions | | | | --- | --- | | `[async](testing/async)` | **Deprecated:** use `[waitForAsync](testing/waitforasync)()`, (expected removal in v12) | | `[discardPeriodicTasks](testing/discardperiodictasks)` | Discard all remaining periodic tasks. | | `[fakeAsync](testing/fakeasync)` | Wraps a function to be executed in the `[fakeAsync](testing/fakeasync)` zone:* Microtasks are manually executed by calling `[flushMicrotasks](testing/flushmicrotasks)()`. * Timers are synchronous; `[tick](testing/tick)()` simulates the asynchronous passage of time. | | `[flush](testing/flush)` | Flushes any pending microtasks and simulates the asynchronous passage of time for the timers in the `[fakeAsync](testing/fakeasync)` zone by draining the macrotask queue until it is empty. | | `[flushMicrotasks](testing/flushmicrotasks)` | Flush any pending microtasks. | | `[getTestBed](testing/gettestbed)` | Returns a singleton of the `[TestBed](testing/testbed)` class. | | `[inject](testing/inject)` | Allows injecting dependencies in `beforeEach()` and `it()`. Note: this function (imported from the `@angular/core/testing` package) can **only** be used to inject dependencies in tests. To inject dependencies in your application code, use the [`inject`](inject) function from the `@angular/core` package instead. | | `[resetFakeAsyncZone](testing/resetfakeasynczone)` | Clears out the shared fake async zone for a test. To be called in a global `beforeEach`. | | `[tick](testing/tick)` | Simulates the asynchronous passage of time for the timers in the `[fakeAsync](testing/fakeasync)` zone. | | `[waitForAsync](testing/waitforasync)` | Wraps a test function in an asynchronous test zone. The test will automatically complete when all asynchronous calls within this zone are done. Can be used to wrap an [`inject`](testing/inject) call. | | `[withModule](testing/withmodule)` | | ### Structures | | | | --- | --- | | `[ModuleTeardownOptions](testing/moduleteardownoptions)` | Configures the test module teardown behavior in `[TestBed](testing/testbed)`. | | `[TestBedStatic](testing/testbedstatic)` | Static methods implemented by the `[TestBed](testing/testbed)`. | | `[TestEnvironmentOptions](testing/testenvironmentoptions)` | | | `[TestModuleMetadata](testing/testmodulemetadata)` | | ### Types | | | | --- | --- | | `[ComponentFixtureAutoDetect](testing/componentfixtureautodetect)` | | | `[ComponentFixtureNoNgZone](testing/componentfixturenongzone)` | | | `[MetadataOverride](testing/metadataoverride)` | Type used for modifications to metadata | angular IterableDiffer IterableDiffer ============== `interface` A strategy for tracking changes over time to an iterable. Used by [`NgForOf`](../common/ngforof) to respond to changes in an iterable by effecting equivalent changes in the DOM. ``` interface IterableDiffer<V> { diff(object: NgIterable<V>): IterableChanges<V> | null } ``` Class implementations --------------------- * `[DefaultIterableDiffer](defaultiterablediffer)` Methods ------- | diff() | | --- | | Compute a difference between the previous state and the new `object` state. | | `diff(object: NgIterable<V>): IterableChanges<V> | null` Parameters | | | | | --- | --- | --- | | `object` | `[NgIterable](ngiterable)<V>` | containing the new value. | Returns `[IterableChanges](iterablechanges)<V> | null`: an object describing the difference. The return value is only valid until the next `diff()` invocation. | angular CompilerOptions CompilerOptions =============== `type-alias` Options for creating a compiler. [See more...](compileroptions#description) ``` type CompilerOptions = { useJit?: boolean; defaultEncapsulation?: ViewEncapsulation; providers?: StaticProvider[]; missingTranslation?: MissingTranslationStrategy; preserveWhitespaces?: boolean; }; ``` Description ----------- Note: the `useJit` and `missingTranslation` config options are not used in Ivy, passing them has no effect. Those config options are deprecated since v13. angular ValueProvider ValueProvider ============= `interface` Configures the `[Injector](injector)` to return a value for a token. ``` interface ValueProvider extends ValueSansProvider { provide: any multi?: boolean // inherited from core/ValueSansProvider useValue: any } ``` See also -------- * ["Dependency Injection Guide"](../../guide/dependency-injection). Properties ---------- | Property | Description | | --- | --- | | `provide: any` | An injection token. Typically an instance of `[Type](type)` or `[InjectionToken](injectiontoken)`, but can be `any`. | | `multi?: boolean` | When true, injector returns an array of instances. This is useful to allow multiple providers spread across many files to provide configuration information to a common token. | Usage notes ----------- ### Example ``` const injector = Injector.create({providers: [{provide: String, useValue: 'Hello'}]}); expect(injector.get(String)).toEqual('Hello'); ``` ### Multi-value example ``` const locale = new InjectionToken<string[]>('locale'); const injector = Injector.create({ providers: [ {provide: locale, multi: true, useValue: 'en'}, {provide: locale, multi: true, useValue: 'sk'}, ] }); const locales: string[] = injector.get(locale); expect(locales).toEqual(['en', 'sk']); ``` angular LOCALE_ID LOCALE\_ID ========== `const` Provide this token to set the locale of your application. It is used for i18n extraction, by i18n pipes (DatePipe, I18nPluralPipe, CurrencyPipe, DecimalPipe and PercentPipe) and by ICU expressions. [See more...](locale_id#description) ### `const LOCALE_ID: InjectionToken<string>;` #### Description See the [i18n guide](../../guide/i18n-common-locale-id) for more information. Further information is available in the [Usage Notes...](locale_id#usage-notes) Usage notes ----------- #### Example ``` import { LOCALE_ID } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; platformBrowserDynamic().bootstrapModule(AppModule, { providers: [{provide: LOCALE_ID, useValue: 'en-US' }] }); ``` angular ENVIRONMENT_INITIALIZER ENVIRONMENT\_INITIALIZER ======================== `const` A multi-provider token for initialization functions that will run upon construction of an environment injector. ### `const ENVIRONMENT_INITIALIZER: InjectionToken<() => void>;` angular Injectable Injectable ========== `decorator` Decorator that marks a class as available to be provided and injected as a dependency. | Option | Description | | --- | --- | | [`providedIn?`](injectable#providedIn) | Determines which injectors will provide the injectable. | See also -------- * [Introduction to Services and DI](../../guide/architecture-services) * [Dependency Injection Guide](../../guide/dependency-injection) Options ------- | providedIn | | --- | | Determines which injectors will provide the injectable. | | `providedIn?: Type<any> | 'root' | 'platform' | 'any' | null` | | * `[Type](type)<any>` - associates the injectable with an `@[NgModule](ngmodule)` or other `[InjectorType](injectortype)`. This option is DEPRECATED. * 'null' : Equivalent to `undefined`. The injectable is not provided in any scope automatically and must be added to a `providers` array of an [@NgModule](ngmodule#providers), [@Component](directive#providers) or [@Directive](directive#providers). The following options specify that this injectable should be provided in one of the following injectors:* 'root' : The application-level injector in most apps. * 'platform' : A special singleton platform injector shared by all applications on the page. * 'any' : Provides a unique instance in each lazy loaded module while all eagerly loaded modules share one instance. This option is DEPRECATED. | Usage notes ----------- Marking a class with `@[Injectable](injectable)` ensures that the compiler will generate the necessary metadata to create the class's dependencies when the class is injected. The following example shows how a service class is properly marked so that a supporting service can be injected upon creation. ``` @Injectable() class UsefulService { } @Injectable() class NeedsService { constructor(public service: UsefulService) {} } const injector = Injector.create({ providers: [{provide: NeedsService, deps: [UsefulService]}, {provide: UsefulService, deps: []}] }); expect(injector.get(NeedsService).service instanceof UsefulService).toBe(true); ``` angular NgModuleRef NgModuleRef =========== `class` Represents an instance of an `[NgModule](ngmodule)` created by an `[NgModuleFactory](ngmodulefactory)`. Provides access to the `[NgModule](ngmodule)` instance and related objects. ``` abstract class NgModuleRef<T> { abstract injector: EnvironmentInjector abstract componentFactoryResolver: ComponentFactoryResolver abstract instance: T abstract destroy(): void abstract onDestroy(callback: () => void): void } ``` Properties ---------- | Property | Description | | --- | --- | | `abstract injector: [EnvironmentInjector](environmentinjector)` | Read-Only The injector that contains all of the providers of the `[NgModule](ngmodule)`. | | `abstract componentFactoryResolver: [ComponentFactoryResolver](componentfactoryresolver)` | Read-Only The resolver that can retrieve component factories in a context of this module. Note: since v13, dynamic component creation via [`ViewContainerRef.createComponent`](viewcontainerref#createComponent) does **not** require resolving component factory: component class can be used directly. **Deprecated** Angular no longer requires Component factories. Please use other APIs where Component class can be used directly. | | `abstract instance: T` | Read-Only The `[NgModule](ngmodule)` instance. | Methods ------- | destroy() | | --- | | Destroys the module instance and all of the data structures associated with it. | | `abstract destroy(): void` Parameters There are no parameters. Returns `void` | | onDestroy() | | --- | | Registers a callback to be executed when the module is destroyed. | | `abstract onDestroy(callback: () => void): void` Parameters | | | | | --- | --- | --- | | `callback` | `() => void` | | Returns `void` |
programming_docs
angular resolveForwardRef resolveForwardRef ================= `function` Lazily retrieves the reference value from a forwardRef. [See more...](resolveforwardref#description) ### `resolveForwardRef<T>(type: T): T` ###### Parameters | | | | | --- | --- | --- | | `type` | `T` | | ###### Returns `T` See also -------- * `[forwardRef](forwardref)` Description ----------- Acts as the identity function when given a non-forward-ref value. Further information is available in the [Usage Notes...](resolveforwardref#usage-notes) Usage notes ----------- ### Example ``` const ref = forwardRef(() => 'refValue'); expect(resolveForwardRef(ref as any)).toEqual('refValue'); expect(resolveForwardRef('regularValue')).toEqual('regularValue'); ``` angular NgModule NgModule ======== `decorator` Decorator that marks a class as an NgModule and supplies configuration metadata. | Option | Description | | --- | --- | | [`providers?`](ngmodule#providers) | The set of injectable objects that are available in the injector of this module. | | [`declarations?`](ngmodule#declarations) | The set of components, directives, and pipes ([declarables](../../guide/glossary#declarable)) that belong to this module. | | [`imports?`](ngmodule#imports) | The set of NgModules whose exported [declarables](../../guide/glossary#declarable) are available to templates in this module. | | [`exports?`](ngmodule#exports) | The set of components, directives, and pipes declared in this NgModule that can be used in the template of any component that is part of an NgModule that imports this NgModule. Exported declarations are the module's public API. | | [`entryComponents?`](ngmodule#entryComponents) | The set of components to compile when this NgModule is defined, so that they can be dynamically loaded into the view. | | [`bootstrap?`](ngmodule#bootstrap) | The set of components that are bootstrapped when this module is bootstrapped. The components listed here are automatically added to `entryComponents`. | | [`schemas?`](ngmodule#schemas) | The set of schemas that declare elements to be allowed in the NgModule. Elements and properties that are neither Angular components nor directives must be declared in a schema. | | [`id?`](ngmodule#id) | A name or path that uniquely identifies this NgModule in `[getNgModuleById](getngmodulebyid)`. If left `undefined`, the NgModule is not registered with `[getNgModuleById](getngmodulebyid)`. | | [`jit?`](ngmodule#jit) | When present, this module is ignored by the AOT compiler. It remains in distributed code, and the JIT compiler attempts to compile it at run time, in the browser. To ensure the correct behavior, the app must import `@angular/compiler`. | Options ------- | providers | | --- | | The set of injectable objects that are available in the injector of this module. | | `providers?: Array<Provider | EnvironmentProviders>` | | Dependencies whose providers are listed here become available for injection into any component, directive, pipe or service that is a child of this injector. The NgModule used for bootstrapping uses the root injector, and can provide dependencies to any part of the app. A lazy-loaded module has its own injector, typically a child of the app root injector. Lazy-loaded services are scoped to the lazy-loaded module's injector. If a lazy-loaded module also provides the `UserService`, any component created within that module's context (such as by router navigation) gets the local instance of the service, not the instance in the root injector. Components in external modules continue to receive the instance provided by their injectors. Example The following example defines a class that is injected in the HelloWorld NgModule: ``` class Greeter { greet(name:string) { return 'Hello ' + name + '!'; } } @NgModule({ providers: [ Greeter ] }) class HelloWorld { greeter:Greeter; constructor(greeter:Greeter) { this.greeter = greeter; } } ``` | | declarations | | --- | | The set of components, directives, and pipes ([declarables](../../guide/glossary#declarable)) that belong to this module. | | `declarations?: Array<Type<any> | any[]>` | | The set of selectors that are available to a template include those declared here, and those that are exported from imported NgModules. Declarables must belong to exactly one module. The compiler emits an error if you try to declare the same class in more than one module. Be careful not to declare a class that is imported from another module. Example The following example allows the CommonModule to use the `[NgFor](../common/ngfor)` directive. ``` @NgModule({ declarations: [NgFor] }) class CommonModule { } ``` | | imports | | --- | | The set of NgModules whose exported [declarables](../../guide/glossary#declarable) are available to templates in this module. | | `imports?: Array<Type<any> | ModuleWithProviders<{}> | any[]>` | | A template can use exported declarables from any imported module, including those from modules that are imported indirectly and re-exported. For example, `ModuleA` imports `ModuleB`, and also exports it, which makes the declarables from `ModuleB` available wherever `ModuleA` is imported. Example The following example allows MainModule to use anything exported by `[CommonModule](../common/commonmodule)`: ``` @NgModule({ imports: [CommonModule] }) class MainModule { } ``` | | exports | | --- | | The set of components, directives, and pipes declared in this NgModule that can be used in the template of any component that is part of an NgModule that imports this NgModule. Exported declarations are the module's public API. | | `exports?: Array<Type<any> | any[]>` | | A declarable belongs to one and only one NgModule. A module can list another module among its exports, in which case all of that module's public declaration are exported. Declarations are private by default. If this ModuleA does not export UserComponent, then only the components within this ModuleA can use UserComponent. ModuleA can import ModuleB and also export it, making exports from ModuleB available to an NgModule that imports ModuleA. Example The following example exports the `[NgFor](../common/ngfor)` directive from CommonModule. ``` @NgModule({ exports: [NgFor] }) class CommonModule { } ``` | | entryComponents | | --- | | The set of components to compile when this NgModule is defined, so that they can be dynamically loaded into the view. | | `entryComponents?: Array<Type<any> | any[]>` | | For each component listed here, Angular creates a `[ComponentFactory](componentfactory)` and stores it in the `[ComponentFactoryResolver](componentfactoryresolver)`. Angular automatically adds components in the module's bootstrap and route definitions into the `entryComponents` list. Use this option to add components that are bootstrapped using one of the imperative techniques, such as `ViewContainerRef.createComponent()`. | | bootstrap | | --- | | The set of components that are bootstrapped when this module is bootstrapped. The components listed here are automatically added to `entryComponents`. | | `bootstrap?: Array<Type<any> | any[]>` | | | | schemas | | --- | | The set of schemas that declare elements to be allowed in the NgModule. Elements and properties that are neither Angular components nor directives must be declared in a schema. | | `schemas?: Array<SchemaMetadata | any[]>` | | Allowed value are `[NO\_ERRORS\_SCHEMA](no_errors_schema)` and `[CUSTOM\_ELEMENTS\_SCHEMA](custom_elements_schema)`. | | id | | --- | | A name or path that uniquely identifies this NgModule in `[getNgModuleById](getngmodulebyid)`. If left `undefined`, the NgModule is not registered with `[getNgModuleById](getngmodulebyid)`. | | `id?: string` | | | | jit | | --- | | When present, this module is ignored by the AOT compiler. It remains in distributed code, and the JIT compiler attempts to compile it at run time, in the browser. To ensure the correct behavior, the app must import `@angular/compiler`. | | `jit?: true` | | | angular Version Version ======= `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Represents the version of Angular ``` class Version { constructor(full: string) major: string minor: string patch: string full: string } ``` Constructor ----------- | | | | | | --- | --- | --- | --- | | `constructor(full: string)` Parameters | | | | | --- | --- | --- | | `full` | `string` | | | Properties ---------- | Property | Description | | --- | --- | | `major: string` | Read-Only | | `minor: string` | Read-Only | | `patch: string` | Read-Only | | `full: string` | Declared in Constructor | angular SchemaMetadata SchemaMetadata ============== `interface` A schema definition associated with an NgModule. ``` interface SchemaMetadata { name: string } ``` See also -------- * `@[NgModule](ngmodule)`, `[CUSTOM\_ELEMENTS\_SCHEMA](custom_elements_schema)`, `[NO\_ERRORS\_SCHEMA](no_errors_schema)` Properties ---------- | Property | Description | | --- | --- | | `name: string` | | angular PlatformRef PlatformRef =========== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` The Angular platform is the entry point for Angular on a web page. Each page has exactly one platform. Services (such as reflection) which are common to every Angular application running on the page are bound in its scope. A page's platform is initialized implicitly when a platform is created using a platform factory such as `PlatformBrowser`, or explicitly by calling the `[createPlatform](createplatform)()` function. ``` class PlatformRef { injector: Injector destroyed bootstrapModuleFactory<M>(moduleFactory: NgModuleFactory<M>, options?: BootstrapOptions): Promise<NgModuleRef<M>> bootstrapModule<M>(moduleType: Type<M>, compilerOptions: (CompilerOptions & BootstrapOptions) | (CompilerOptions & BootstrapOptions)[] = []): Promise<NgModuleRef<M>> onDestroy(callback: () => void): void destroy() } ``` Provided in ----------- * ``` 'platform' ``` Properties ---------- | Property | Description | | --- | --- | | `injector: [Injector](injector)` | Read-Only Retrieves the platform [`Injector`](injector), which is the parent injector for every Angular application on the page and provides singleton providers. | | `destroyed` | Read-Only Indicates whether this instance was destroyed. | Methods ------- | bootstrapModuleFactory() | | --- | | Creates an instance of an `@[NgModule](ngmodule)` for the given platform. | | `bootstrapModuleFactory<M>(moduleFactory: NgModuleFactory<M>, options?: BootstrapOptions): Promise<NgModuleRef<M>>` **Deprecated** Passing NgModule factories as the `PlatformRef.bootstrapModuleFactory` function argument is deprecated. Use the `PlatformRef.bootstrapModule` API instead. Parameters | | | | | --- | --- | --- | | `moduleFactory` | `[NgModuleFactory](ngmodulefactory)<M>` | | | `options` | `[BootstrapOptions](bootstrapoptions)` | Optional. Default is `undefined`. | Returns `Promise<[NgModuleRef](ngmoduleref)<M>>` | | bootstrapModule() | | --- | | Creates an instance of an `@[NgModule](ngmodule)` for a given platform. | | `bootstrapModule<M>(moduleType: Type<M>, compilerOptions: (CompilerOptions & BootstrapOptions) | (CompilerOptions & BootstrapOptions)[] = []): Promise<NgModuleRef<M>>` Parameters | | | | | --- | --- | --- | | `moduleType` | `[Type](type)<M>` | | | `compilerOptions` | `([CompilerOptions](compileroptions) & [BootstrapOptions](bootstrapoptions)) | ([CompilerOptions](compileroptions) & [BootstrapOptions](bootstrapoptions))[]` | Optional. Default is `[]`. | Returns `Promise<[NgModuleRef](ngmoduleref)<M>>` | | Usage Notes Simple Example ``` @NgModule({ imports: [BrowserModule] }) class MyModule {} let moduleRef = platformBrowser().bootstrapModule(MyModule); ``` | | onDestroy() | | --- | | Registers a listener to be called when the platform is destroyed. | | `onDestroy(callback: () => void): void` Parameters | | | | | --- | --- | --- | | `callback` | `() => void` | | Returns `void` | | destroy() | | --- | | Destroys the current Angular platform and all Angular applications on the page. Destroys all modules and listeners registered with the platform. | | `destroy()` Parameters There are no parameters. | angular Renderer2 Renderer2 ========= `class` Extend this base class to implement custom rendering. By default, Angular renders a template into DOM. You can use custom rendering to intercept rendering calls, or to render to something other than DOM. [See more...](renderer2#description) ``` abstract class Renderer2 { abstract data: {...} destroyNode: ((node: any) => void) | null abstract destroy(): void abstract createElement(name: string, namespace?: string): any abstract createComment(value: string): any abstract createText(value: string): any abstract appendChild(parent: any, newChild: any): void abstract insertBefore(parent: any, newChild: any, refChild: any, isMove?: boolean): void abstract removeChild(parent: any, oldChild: any, isHostElement?: boolean): void abstract selectRootElement(selectorOrNode: any, preserveContent?: boolean): any abstract parentNode(node: any): any abstract nextSibling(node: any): any abstract setAttribute(el: any, name: string, value: string, namespace?: string): void abstract removeAttribute(el: any, name: string, namespace?: string): void abstract addClass(el: any, name: string): void abstract removeClass(el: any, name: string): void abstract setStyle(el: any, style: string, value: any, flags?: RendererStyleFlags2): void abstract removeStyle(el: any, style: string, flags?: RendererStyleFlags2): void abstract setProperty(el: any, name: string, value: any): void abstract setValue(node: any, value: string): void abstract listen(target: any, eventName: string, callback: (event: any) => boolean | void): () => void } ``` Description ----------- Create your custom renderer using `[RendererFactory2](rendererfactory2)`. Use a custom renderer to bypass Angular's templating and make custom UI changes that can't be expressed declaratively. For example if you need to set a property or an attribute whose name is not statically known, use the `setProperty()` or `setAttribute()` method. Properties ---------- | Property | Description | | --- | --- | | `abstract data: { [key: string]: any; }` | Read-Only Use to store arbitrary developer-defined data on a renderer instance, as an object containing key-value pairs. This is useful for renderers that delegate to other renderers. | | `destroyNode: ((node: any) => void) | null` | If null or undefined, the view engine won't call it. This is used as a performance optimization for production mode. | Methods ------- | destroy() | | --- | | Implement this callback to destroy the renderer or the host element. | | `abstract destroy(): void` Parameters There are no parameters. Returns `void` | | createElement() | | --- | | Implement this callback to create an instance of the host element. | | `abstract createElement(name: string, namespace?: string): any` Parameters | | | | | --- | --- | --- | | `name` | `string` | An identifying name for the new element, unique within the namespace. | | `namespace` | `string` | The namespace for the new element. Optional. Default is `undefined`. | Returns `any`: The new element. | | createComment() | | --- | | Implement this callback to add a comment to the DOM of the host element. | | `abstract createComment(value: string): any` Parameters | | | | | --- | --- | --- | | `value` | `string` | The comment text. | Returns `any`: The modified element. | | createText() | | --- | | Implement this callback to add text to the DOM of the host element. | | `abstract createText(value: string): any` Parameters | | | | | --- | --- | --- | | `value` | `string` | The text string. | Returns `any`: The modified element. | | appendChild() | | --- | | Appends a child to a given parent node in the host element DOM. | | `abstract appendChild(parent: any, newChild: any): void` Parameters | | | | | --- | --- | --- | | `parent` | `any` | The parent node. | | `newChild` | `any` | The new child node. | Returns `void` | | insertBefore() | | --- | | Implement this callback to insert a child node at a given position in a parent node in the host element DOM. | | `abstract insertBefore(parent: any, newChild: any, refChild: any, isMove?: boolean): void` Parameters | | | | | --- | --- | --- | | `parent` | `any` | The parent node. | | `newChild` | `any` | The new child nodes. | | `refChild` | `any` | The existing child node before which `newChild` is inserted. | | `isMove` | `boolean` | Optional argument which signifies if the current `insertBefore` is a result of a move. Animation uses this information to trigger move animations. In the past the Animation would always assume that any `insertBefore` is a move. This is not strictly true because with runtime i18n it is possible to invoke `insertBefore` as a result of i18n and it should not trigger an animation move. Optional. Default is `undefined`. | Returns `void` | | removeChild() | | --- | | Implement this callback to remove a child node from the host element's DOM. | | `abstract removeChild(parent: any, oldChild: any, isHostElement?: boolean): void` Parameters | | | | | --- | --- | --- | | `parent` | `any` | The parent node. | | `oldChild` | `any` | The child node to remove. | | `isHostElement` | `boolean` | Optionally signal to the renderer whether this element is a host element or not Optional. Default is `undefined`. | Returns `void` | | selectRootElement() | | --- | | Implement this callback to prepare an element to be bootstrapped as a root element, and return the element instance. | | `abstract selectRootElement(selectorOrNode: any, preserveContent?: boolean): any` Parameters | | | | | --- | --- | --- | | `selectorOrNode` | `any` | The DOM element. | | `preserveContent` | `boolean` | Whether the contents of the root element should be preserved, or cleared upon bootstrap (default behavior). Use with `[ViewEncapsulation.ShadowDom](viewencapsulation#ShadowDom)` to allow simple native content projection via `<slot>` elements. Optional. Default is `undefined`. | Returns `any`: The root element. | | parentNode() | | --- | | Implement this callback to get the parent of a given node in the host element's DOM. | | `abstract parentNode(node: any): any` Parameters | | | | | --- | --- | --- | | `node` | `any` | The child node to query. | Returns `any`: The parent node, or null if there is no parent. For WebWorkers, always returns true. This is because the check is synchronous, and the caller can't rely on checking for null. | | nextSibling() | | --- | | Implement this callback to get the next sibling node of a given node in the host element's DOM. | | `abstract nextSibling(node: any): any` Parameters | | | | | --- | --- | --- | | `node` | `any` | | Returns `any`: The sibling node, or null if there is no sibling. For WebWorkers, always returns a value. This is because the check is synchronous, and the caller can't rely on checking for null. | | setAttribute() | | --- | | Implement this callback to set an attribute value for an element in the DOM. | | `abstract setAttribute(el: any, name: string, value: string, namespace?: string): void` Parameters | | | | | --- | --- | --- | | `el` | `any` | The element. | | `name` | `string` | The attribute name. | | `value` | `string` | The new value. | | `namespace` | `string` | The namespace. Optional. Default is `undefined`. | Returns `void` | | removeAttribute() | | --- | | Implement this callback to remove an attribute from an element in the DOM. | | `abstract removeAttribute(el: any, name: string, namespace?: string): void` Parameters | | | | | --- | --- | --- | | `el` | `any` | The element. | | `name` | `string` | The attribute name. | | `namespace` | `string` | The namespace. Optional. Default is `undefined`. | Returns `void` | | addClass() | | --- | | Implement this callback to add a class to an element in the DOM. | | `abstract addClass(el: any, name: string): void` Parameters | | | | | --- | --- | --- | | `el` | `any` | The element. | | `name` | `string` | The class name. | Returns `void` | | removeClass() | | --- | | Implement this callback to remove a class from an element in the DOM. | | `abstract removeClass(el: any, name: string): void` Parameters | | | | | --- | --- | --- | | `el` | `any` | The element. | | `name` | `string` | The class name. | Returns `void` | | setStyle() | | --- | | Implement this callback to set a CSS style for an element in the DOM. | | `abstract setStyle(el: any, style: string, value: any, flags?: RendererStyleFlags2): void` Parameters | | | | | --- | --- | --- | | `el` | `any` | The element. | | `[style](../animations/style)` | `string` | The name of the style. | | `value` | `any` | The new value. | | `flags` | `[RendererStyleFlags2](rendererstyleflags2)` | Flags for style variations. No flags are set by default. Optional. Default is `undefined`. | Returns `void` | | removeStyle() | | --- | | Implement this callback to remove the value from a CSS style for an element in the DOM. | | `abstract removeStyle(el: any, style: string, flags?: RendererStyleFlags2): void` Parameters | | | | | --- | --- | --- | | `el` | `any` | The element. | | `[style](../animations/style)` | `string` | The name of the style. | | `flags` | `[RendererStyleFlags2](rendererstyleflags2)` | Flags for style variations to remove, if set. ??? Optional. Default is `undefined`. | Returns `void` | | setProperty() | | --- | | Implement this callback to set the value of a property of an element in the DOM. | | `abstract setProperty(el: any, name: string, value: any): void` Parameters | | | | | --- | --- | --- | | `el` | `any` | The element. | | `name` | `string` | The property name. | | `value` | `any` | The new value. | Returns `void` | | setValue() | | --- | | Implement this callback to set the value of a node in the host element. | | `abstract setValue(node: any, value: string): void` Parameters | | | | | --- | --- | --- | | `node` | `any` | The node. | | `value` | `string` | The new value. | Returns `void` | | listen() | | --- | | Implement this callback to start an event listener. | | `abstract listen(target: any, eventName: string, callback: (event: any) => boolean | void): () => void` Parameters | | | | | --- | --- | --- | | `target` | `any` | The context in which to listen for events. Can be the entire window or document, the body of the document, or a specific DOM element. | | `eventName` | `string` | The event to listen for. | | `callback` | `(event: any) => boolean | void` | A handler function to invoke when the event occurs. | Returns `() => void`: An "unlisten" function for disposing of this handler. |
programming_docs
angular isDevMode isDevMode ========= `function` Returns whether Angular is in development mode. [See more...](isdevmode#description) ### `isDevMode(): boolean` ###### Parameters There are no parameters. ###### Returns `boolean` See also -------- * [ng build](cli/build) Description ----------- By default, this is true, unless `[enableProdMode](enableprodmode)` is invoked prior to calling this method or the application is built using the Angular CLI with the `optimization` option. angular ChangeDetectionStrategy ChangeDetectionStrategy ======================= `enum` The strategy that the default change detector uses to detect changes. When set, takes effect the next time change detection is triggered. See also -------- * [Change detection usage](changedetectorref#usage-notes) ``` enum ChangeDetectionStrategy { OnPush: 0 Default: 1 } ``` Members ------- | Member | Description | | --- | --- | | `OnPush: 0` | Use the `CheckOnce` strategy, meaning that automatic change detection is deactivated until reactivated by setting the strategy to `Default` (`CheckAlways`). Change detection can still be explicitly invoked. This strategy applies to all child directives and cannot be overridden. | | `Default: 1` | Use the default `CheckAlways` strategy, in which change detection is automatic until explicitly deactivated. | angular TypeDecorator TypeDecorator ============= `interface` An interface implemented by all Angular type decorators, which allows them to be used as decorators as well as Angular syntax. [See more...](typedecorator#description) ``` interface TypeDecorator { <T extends Type<any>>(type: T): T } ``` Description ----------- ``` @ng.Component({...}) class MyClass {...} ``` Methods ------- | *call signature* | | --- | | Invoke as decorator. | | `<T extends Type<any>>(type: T): T` Parameters | | | | | --- | --- | --- | | `type` | `T` | | Returns `T` | | `(target: Object, propertyKey?: string | symbol, parameterIndex?: number): void` Parameters | | | | | --- | --- | --- | | `target` | `Object` | | | `propertyKey` | `string | symbol` | Optional. Default is `undefined`. | | `parameterIndex` | `number` | Optional. Default is `undefined`. | Returns `void` | angular PACKAGE_ROOT_URL PACKAGE\_ROOT\_URL ================== `const` A [DI token](../../guide/glossary#di-token "DI token definition") that indicates the root directory of the application ### `const PACKAGE_ROOT_URL: InjectionToken<string>;` angular SkipSelf SkipSelf ======== `decorator` Parameter decorator to be used on constructor parameters, which tells the DI framework to start dependency resolution from the parent injector. Resolution works upward through the injector hierarchy, so the local injector is not checked for a provider. See also -------- * [Dependency Injection guide](../../guide/dependency-injection-in-action#skip). * `[Self](self)` * `[Optional](optional)` Options ------- Usage notes ----------- In the following example, the dependency can be resolved when instantiating a child, but not when instantiating the class itself. ``` class Dependency {} @Injectable() class NeedsDependency { constructor(@SkipSelf() public dependency: Dependency) {} } const parent = Injector.create({providers: [{provide: Dependency, deps: []}]}); const child = Injector.create({providers: [{provide: NeedsDependency, deps: [Dependency]}], parent}); expect(child.get(NeedsDependency).dependency instanceof Dependency).toBe(true); const inj = Injector.create( {providers: [{provide: NeedsDependency, deps: [[new Self(), Dependency]]}]}); expect(() => inj.get(NeedsDependency)).toThrowError(); ``` angular OnDestroy OnDestroy ========= `interface` A lifecycle hook that is called when a directive, pipe, or service is destroyed. Use for any custom cleanup that needs to occur when the instance is destroyed. ``` interface OnDestroy { ngOnDestroy(): void } ``` Class implementations --------------------- * `[NgComponentOutlet](../common/ngcomponentoutlet)` * `[AsyncPipe](../common/asyncpipe)` * `[NgOptimizedImage](../common/ngoptimizedimage)` * `[HashLocationStrategy](../common/hashlocationstrategy)` * `[Location](../common/location)` + `[SpyLocation](../common/testing/spylocation)` * `[PathLocationStrategy](../common/pathlocationstrategy)` * `[AbstractFormGroupDirective](../forms/abstractformgroupdirective)` + `[NgModelGroup](../forms/ngmodelgroup)` + `[FormGroupName](../forms/formgroupname)` * `[NgModel](../forms/ngmodel)` * `[NgModelGroup](../forms/ngmodelgroup)` * `[RadioControlValueAccessor](../forms/radiocontrolvalueaccessor)` * `[FormControlDirective](../forms/formcontroldirective)` * `[FormControlName](../forms/formcontrolname)` * `[FormGroupDirective](../forms/formgroupdirective)` * `[FormArrayName](../forms/formarrayname)` * `[FormGroupName](../forms/formgroupname)` * `[NgSelectOption](../forms/ngselectoption)` * `[RouterLink](../router/routerlink)` * `[RouterLinkWithHref](../router/routerlinkwithhref)` * `[RouterLinkActive](../router/routerlinkactive)` * `[RouterOutlet](../router/routeroutlet)` * `[RouterPreloader](../router/routerpreloader)` * `[UpgradeComponent](../upgrade/static/upgradecomponent)` See also -------- * [Lifecycle hooks guide](../../guide/lifecycle-hooks) Methods ------- | ngOnDestroy() | | --- | | A callback method that performs custom clean-up, invoked immediately before a directive, pipe, or service instance is destroyed. | | `ngOnDestroy(): void` Parameters There are no parameters. Returns `void` | Usage notes ----------- The following snippet shows how a component can implement this interface to define its own custom clean-up method. ``` @Component({selector: 'my-cmp', template: `...`}) class MyComponent implements OnDestroy { ngOnDestroy() { // ... } } ``` angular ApplicationModule ApplicationModule ================= `ngmodule` Re-exported by `[BrowserModule](../platform-browser/browsermodule)`, which is included automatically in the root `AppModule` when you create a new app with the CLI `new` command. Eagerly injects `[ApplicationRef](applicationref)` to instantiate it. ``` class ApplicationModule { } ``` angular IterableChanges IterableChanges =============== `interface` An object describing the changes in the `Iterable` collection since last time `[IterableDiffer](iterablediffer)#diff()` was invoked. ``` interface IterableChanges<V> { forEachItem(fn: (record: IterableChangeRecord<V>) => void): void forEachOperation(fn: (record: IterableChangeRecord<V>, previousIndex: number, currentIndex: number) => void): void forEachPreviousItem(fn: (record: IterableChangeRecord<V>) => void): void forEachAddedItem(fn: (record: IterableChangeRecord<V>) => void): void forEachMovedItem(fn: (record: IterableChangeRecord<V>) => void): void forEachRemovedItem(fn: (record: IterableChangeRecord<V>) => void): void forEachIdentityChange(fn: (record: IterableChangeRecord<V>) => void): void } ``` Class implementations --------------------- * `[DefaultIterableDiffer](defaultiterablediffer)` Methods ------- | forEachItem() | | --- | | Iterate over all changes. `[IterableChangeRecord](iterablechangerecord)` will contain information about changes to each item. | | `forEachItem(fn: (record: IterableChangeRecord<V>) => void): void` Parameters | | | | | --- | --- | --- | | `fn` | `(record: [IterableChangeRecord](iterablechangerecord)<V>) => void` | | Returns `void` | | forEachOperation() | | --- | | Iterate over a set of operations which when applied to the original `Iterable` will produce the new `Iterable`. | | `forEachOperation(fn: (record: IterableChangeRecord<V>, previousIndex: number, currentIndex: number) => void): void` Parameters | | | | | --- | --- | --- | | `fn` | `(record: [IterableChangeRecord](iterablechangerecord)<V>, previousIndex: number, currentIndex: number) => void` | | Returns `void` | | NOTE: These are not necessarily the actual operations which were applied to the original `Iterable`, rather these are a set of computed operations which may not be the same as the ones applied. | | forEachPreviousItem() | | --- | | Iterate over changes in the order of original `Iterable` showing where the original items have moved. | | `forEachPreviousItem(fn: (record: IterableChangeRecord<V>) => void): void` Parameters | | | | | --- | --- | --- | | `fn` | `(record: [IterableChangeRecord](iterablechangerecord)<V>) => void` | | Returns `void` | | forEachAddedItem() | | --- | | Iterate over all added items. | | `forEachAddedItem(fn: (record: IterableChangeRecord<V>) => void): void` Parameters | | | | | --- | --- | --- | | `fn` | `(record: [IterableChangeRecord](iterablechangerecord)<V>) => void` | | Returns `void` | | forEachMovedItem() | | --- | | Iterate over all moved items. | | `forEachMovedItem(fn: (record: IterableChangeRecord<V>) => void): void` Parameters | | | | | --- | --- | --- | | `fn` | `(record: [IterableChangeRecord](iterablechangerecord)<V>) => void` | | Returns `void` | | forEachRemovedItem() | | --- | | Iterate over all removed items. | | `forEachRemovedItem(fn: (record: IterableChangeRecord<V>) => void): void` Parameters | | | | | --- | --- | --- | | `fn` | `(record: [IterableChangeRecord](iterablechangerecord)<V>) => void` | | Returns `void` | | forEachIdentityChange() | | --- | | Iterate over all items which had their identity (as computed by the `[TrackByFunction](trackbyfunction)`) changed. | | `forEachIdentityChange(fn: (record: IterableChangeRecord<V>) => void): void` Parameters | | | | | --- | --- | --- | | `fn` | `(record: [IterableChangeRecord](iterablechangerecord)<V>) => void` | | Returns `void` | angular InjectionToken InjectionToken ============== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Creates a token that can be used in a DI Provider. [See more...](injectiontoken#description) ``` class InjectionToken<T> { constructor(_desc: string, options?: { providedIn?: "root" | Type<any> | "platform" | "any"; factory: () => T; }) protected _desc: string toString(): string } ``` Description ----------- Use an `[InjectionToken](injectiontoken)` whenever the type you are injecting is not reified (does not have a runtime representation) such as when injecting an interface, callable type, array or parameterized type. `[InjectionToken](injectiontoken)` is parameterized on `T` which is the type of object which will be returned by the `[Injector](injector)`. This provides an additional level of type safety. ``` interface MyInterface {...} const myInterface = injector.get(new InjectionToken<MyInterface>('SomeToken')); // myInterface is inferred to be MyInterface. ``` When creating an `[InjectionToken](injectiontoken)`, you can optionally specify a factory function which returns (possibly by creating) a default value of the parameterized type `T`. This sets up the `[InjectionToken](injectiontoken)` using this factory as a provider as if it was defined explicitly in the application's root injector. If the factory function, which takes zero arguments, needs to inject dependencies, it can do so using the `inject` function. As you can see in the Tree-shakable InjectionToken example below. Additionally, if a `factory` is specified you can also specify the `providedIn` option, which overrides the above behavior and marks the token as belonging to a particular `@[NgModule](ngmodule)` (note: this option is now deprecated). As mentioned above, `'root'` is the default value for `providedIn`. The `providedIn: [NgModule](ngmodule)` and `providedIn: 'any'` options are deprecated. Further information is available in the [Usage Notes...](injectiontoken#usage-notes) Constructor ----------- | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | | `constructor(_desc: string, options?: { providedIn?: "root" | Type<any> | "platform" | "any"; factory: () => T; })` Parameters | | | | | --- | --- | --- | | `_desc` | `string` | Description for the token, used only for debugging purposes, it should but does not need to be unique | | `options` | `object` | Options for the token's usage, as described above Optional. Default is `undefined`. | | Properties ---------- | Property | Description | | --- | --- | | `protected \_desc: string` | Declared in Constructor Description for the token, used only for debugging purposes, it should but does not need to be unique | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | Usage notes ----------- ### Basic Examples ### Plain InjectionToken ``` const BASE_URL = new InjectionToken<string>('BaseUrl'); const injector = Injector.create({providers: [{provide: BASE_URL, useValue: 'http://localhost'}]}); const url = injector.get(BASE_URL); // Note: since `BASE_URL` is `InjectionToken<string>` // `url` is correctly inferred to be `string` expect(url).toBe('http://localhost'); ``` ### Tree-shakable InjectionToken ``` class MyService { constructor(readonly myDep: MyDep) {} } const MY_SERVICE_TOKEN = new InjectionToken<MyService>('Manually constructed MyService', { providedIn: 'root', factory: () => new MyService(inject(MyDep)), }); const instance = injector.get(MY_SERVICE_TOKEN); expect(instance instanceof MyService).toBeTruthy(); expect(instance.myDep instanceof MyDep).toBeTruthy(); ``` angular EmbeddedViewRef EmbeddedViewRef =============== `class` Represents an Angular [view](../../guide/glossary#view) in a view container. An [embedded view](../../guide/glossary#view-tree) can be referenced from a component other than the hosting component whose template defines it, or it can be defined independently by a `[TemplateRef](templateref)`. [See more...](embeddedviewref#description) ``` abstract class EmbeddedViewRef<C> extends ViewRef { abstract context: C abstract rootNodes: any[] // inherited from core/ViewRef abstract destroyed: boolean abstract destroy(): void abstract onDestroy(callback: Function): any // inherited from core/ChangeDetectorRef abstract markForCheck(): void abstract detach(): void abstract detectChanges(): void abstract checkNoChanges(): void abstract reattach(): void } ``` See also -------- * `[ViewContainerRef](viewcontainerref)` Description ----------- Properties of elements in a view can change, but the structure (number and order) of elements in a view cannot. Change the structure of elements by inserting, moving, or removing nested views in a view container. Further information is available in the [Usage Notes...](embeddedviewref#usage-notes) Properties ---------- | Property | Description | | --- | --- | | `abstract context: C` | The context for this view, inherited from the anchor element. | | `abstract rootNodes: any[]` | Read-Only The root nodes for this embedded view. | Usage notes ----------- The following template breaks down into two separate `[TemplateRef](templateref)` instances, an outer one and an inner one. ``` Count: {{items.length}} <ul> <li *ngFor="let item of items">{{item}}</li> </ul> ``` This is the outer `[TemplateRef](templateref)`: ``` Count: {{items.length}} <ul> <ng-template ngFor let-item [ngForOf]="items"></ng-template> </ul> ``` This is the inner `[TemplateRef](templateref)`: ``` <li>{{item}}</li> ``` The outer and inner `[TemplateRef](templateref)` instances are assembled into views as follows: ``` <!-- ViewRef: outer-0 --> Count: 2 <ul> <ng-template view-container-ref></ng-template> <!-- ViewRef: inner-1 --><li>first</li><!-- /ViewRef: inner-1 --> <!-- ViewRef: inner-2 --><li>second</li><!-- /ViewRef: inner-2 --> </ul> <!-- /ViewRef: outer-0 --> ``` angular async async ===== `function` `deprecated` **Deprecated:** use `[waitForAsync](waitforasync)()`, (expected removal in v12) ### `async(fn: Function): (done: any) => any` **Deprecated** use `[waitForAsync](waitforasync)()`, (expected removal in v12) ###### Parameters | | | | | --- | --- | --- | | `fn` | `Function` | | ###### Returns `(done: any) => any` See also -------- * [`waitForAsync`](waitforasync) angular ComponentFixtureAutoDetect ComponentFixtureAutoDetect ========================== `const` ### `const ComponentFixtureAutoDetect: InjectionToken<boolean[]>;` angular MetadataOverride MetadataOverride ================ `type-alias` Type used for modifications to metadata ``` type MetadataOverride<T> = { add?: Partial<T>; remove?: Partial<T>; set?: Partial<T>; }; ``` angular inject inject ====== `function` Allows injecting dependencies in `beforeEach()` and `it()`. Note: this function (imported from the `@angular/core/testing` package) can **only** be used to inject dependencies in tests. To inject dependencies in your application code, use the [`inject`](../inject) function from the `@angular/core` package instead. [See more...](inject#description) ### `inject(tokens: any[], fn: Function): () => any` ###### Parameters | | | | | --- | --- | --- | | `tokens` | `any[]` | | | `fn` | `Function` | | ###### Returns `() => any` Description ----------- Example: ``` beforeEach(inject([Dependency, AClass], (dep, object) => { // some code that uses `dep` and `object` // ... })); it('...', inject([AClass], (object) => { object.doSomething(); expect(...); }) ``` angular TestEnvironmentOptions TestEnvironmentOptions ====================== `interface` ``` interface TestEnvironmentOptions { teardown?: ModuleTeardownOptions errorOnUnknownElements?: boolean errorOnUnknownProperties?: boolean } ``` Properties ---------- | Property | Description | | --- | --- | | `teardown?: [ModuleTeardownOptions](moduleteardownoptions)` | Configures the test module teardown behavior in `[TestBed](testbed)`. | | `errorOnUnknownElements?: boolean` | Whether errors should be thrown when unknown elements are present in component's template. Defaults to `false`, where the error is simply logged. If set to `true`, the error is thrown. See also:* <https://angular.io/errors/NG8001> for the description of the error and how to fix it | | `errorOnUnknownProperties?: boolean` | Whether errors should be thrown when unknown properties are present in component's template. Defaults to `false`, where the error is simply logged. If set to `true`, the error is thrown. See also:* <https://angular.io/errors/NG8002> for the description of the error and how to fix it | angular ComponentFixtureNoNgZone ComponentFixtureNoNgZone ======================== `const` ### `const ComponentFixtureNoNgZone: InjectionToken<boolean[]>;` angular flushMicrotasks flushMicrotasks =============== `function` Flush any pending microtasks. ### `flushMicrotasks(): void` ###### Parameters There are no parameters. ###### Returns `void` angular tick tick ==== `function` Simulates the asynchronous passage of time for the timers in the `[fakeAsync](fakeasync)` zone. [See more...](tick#description) ### `tick(millis: number = 0, tickOptions: { processNewMacroTasksSynchronously: boolean; } = { processNewMacroTasksSynchronously: true }): void` ###### Parameters | | | | | --- | --- | --- | | `millis` | `number` | The number of milliseconds to advance the virtual timer. Optional. Default is `0`. | | `tickOptions` | `object` | The options to pass to the `<tick>()` function. Optional. Default is `{ processNewMacroTasksSynchronously: true }`. | ###### Returns `void` Description ----------- The microtasks queue is drained at the very start of this function and after any timer callback has been executed. Further information is available in the [Usage Notes...](tick#usage-notes) Usage notes ----------- The `<tick>()` option is a flag called `processNewMacroTasksSynchronously`, which determines whether or not to invoke new macroTasks. If you provide a `tickOptions` object, but do not specify a `processNewMacroTasksSynchronously` property (`<tick>(100, {})`), then `processNewMacroTasksSynchronously` defaults to true. If you omit the `tickOptions` parameter (`<tick>(100))`), then `tickOptions` defaults to `{processNewMacroTasksSynchronously: true}`. ### Example ``` describe('this test', () => { it('looks async but is synchronous', <any>fakeAsync((): void => { let flag = false; setTimeout(() => { flag = true; }, 100); expect(flag).toBe(false); tick(50); expect(flag).toBe(false); tick(50); expect(flag).toBe(true); })); }); ``` The following example includes a nested timeout (new macroTask), and the `tickOptions` parameter is allowed to default. In this case, `processNewMacroTasksSynchronously` defaults to true, and the nested function is executed on each tick. ``` it ('test with nested setTimeout', fakeAsync(() => { let nestedTimeoutInvoked = false; function funcWithNestedTimeout() { setTimeout(() => { nestedTimeoutInvoked = true; }); }; setTimeout(funcWithNestedTimeout); tick(); expect(nestedTimeoutInvoked).toBe(true); })); ``` In the following case, `processNewMacroTasksSynchronously` is explicitly set to false, so the nested timeout function is not invoked. ``` it ('test with nested setTimeout', fakeAsync(() => { let nestedTimeoutInvoked = false; function funcWithNestedTimeout() { setTimeout(() => { nestedTimeoutInvoked = true; }); }; setTimeout(funcWithNestedTimeout); tick(0, {processNewMacroTasksSynchronously: false}); expect(nestedTimeoutInvoked).toBe(false); })); ```
programming_docs
angular discardPeriodicTasks discardPeriodicTasks ==================== `function` Discard all remaining periodic tasks. ### `discardPeriodicTasks(): void` ###### Parameters There are no parameters. ###### Returns `void` angular TestBed TestBed ======= `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Configures and initializes environment for unit testing and provides methods for creating components and services in unit tests. [See more...](testbed#description) ``` class TestBed { platform: PlatformRef ngModule: Type<any> | Type<any>[] initTestEnvironment(ngModule: Type<any> | Type<any>[], platform: PlatformRef, options?: TestEnvironmentOptions): void resetTestEnvironment(): void resetTestingModule(): TestBed configureCompiler(config: { providers?: any[]; useJit?: boolean; }): void configureTestingModule(moduleDef: TestModuleMetadata): TestBed compileComponents(): Promise<any> inject<T>(token: ProviderToken<T>, notFoundValue: undefined, options: InjectOptions & { optional?: false; }): T get<T>(token: ProviderToken<T>, notFoundValue?: T, flags?: InjectFlags): any runInInjectionContext<T>(fn: () => T): T execute(tokens: any[], fn: Function, context?: any): any overrideModule(ngModule: Type<any>, override: MetadataOverride<NgModule>): TestBed overrideComponent(component: Type<any>, override: MetadataOverride<Component>): TestBed overrideDirective(directive: Type<any>, override: MetadataOverride<Directive>): TestBed overridePipe(pipe: Type<any>, override: MetadataOverride<Pipe>): TestBed overrideTemplate(component: Type<any>, template: string): TestBed overrideProvider(token: any, provider: { useFactory: Function; deps: any[]; multi?: boolean; }): TestBed overrideTemplateUsingTestingModule(component: Type<any>, template: string): TestBed createComponent<T>(component: Type<T>): ComponentFixture<T> } ``` Description ----------- `[TestBed](testbed)` is the primary api for writing unit tests for Angular applications and libraries. Properties ---------- | Property | Description | | --- | --- | | `platform: [PlatformRef](../platformref)` | Read-Only | | `ngModule: [Type](../type)<any> | [Type](../type)<any>[]` | Read-Only | Methods ------- | initTestEnvironment() | | --- | | Initialize the environment for testing with a compiler factory, a PlatformRef, and an angular module. These are common to every test in the suite. | | `initTestEnvironment(ngModule: Type<any> | Type<any>[], platform: PlatformRef, options?: TestEnvironmentOptions): void` Parameters | | | | | --- | --- | --- | | `ngModule` | `[Type](../type)<any> | [Type](../type)<any>[]` | | | `platform` | `[PlatformRef](../platformref)` | | | `options` | `[TestEnvironmentOptions](testenvironmentoptions)` | Optional. Default is `undefined`. | Returns `void` | | This may only be called once, to set up the common providers for the current test suite on the current platform. If you absolutely need to change the providers, first use `resetTestEnvironment`. Test modules and platforms for individual platforms are available from '@angular/<platform\_name>/testing'. | | resetTestEnvironment() | | --- | | Reset the providers for the test injector. | | `resetTestEnvironment(): void` Parameters There are no parameters. Returns `void` | | resetTestingModule() | | --- | | `resetTestingModule(): TestBed` Parameters There are no parameters. Returns `[TestBed](testbed)` | | configureCompiler() | | --- | | `configureCompiler(config: { providers?: any[]; useJit?: boolean; }): void` Parameters | | | | | --- | --- | --- | | `config` | `object` | | Returns `void` | | configureTestingModule() | | --- | | `configureTestingModule(moduleDef: TestModuleMetadata): TestBed` Parameters | | | | | --- | --- | --- | | `moduleDef` | `[TestModuleMetadata](testmodulemetadata)` | | Returns `[TestBed](testbed)` | | compileComponents() | | --- | | `compileComponents(): Promise<any>` Parameters There are no parameters. Returns `Promise<any>` | | inject() | | --- | | 4 overloads... Show All Hide All Overload #1 `inject<T>(token: ProviderToken<T>, notFoundValue: null, options: InjectOptions): T | null` Parameters | | | | | --- | --- | --- | | `token` | `[ProviderToken](../providertoken)<T>` | | | `notFoundValue` | `null` | | | `options` | `[InjectOptions](../injectoptions)` | | Returns `T | null` Overload #2 `inject<T>(token: ProviderToken<T>, notFoundValue?: T, options?: InjectOptions): T` Parameters | | | | | --- | --- | --- | | `token` | `[ProviderToken](../providertoken)<T>` | | | `notFoundValue` | `T` | Optional. Default is `undefined`. | | `options` | `[InjectOptions](../injectoptions)` | Optional. Default is `undefined`. | Returns `T` Overload #3 `inject<T>(token: ProviderToken<T>, notFoundValue?: T, flags?: InjectFlags): T` **Deprecated** use object-based flags (`[InjectOptions](../injectoptions)`) instead. Parameters | | | | | --- | --- | --- | | `token` | `[ProviderToken](../providertoken)<T>` | | | `notFoundValue` | `T` | Optional. Default is `undefined`. | | `flags` | `[InjectFlags](../injectflags)` | Optional. Default is `undefined`. | Returns `T` Overload #4 `inject<T>(token: ProviderToken<T>, notFoundValue: null, flags?: InjectFlags): T | null` **Deprecated** use object-based flags (`[InjectOptions](../injectoptions)`) instead. Parameters | | | | | --- | --- | --- | | `token` | `[ProviderToken](../providertoken)<T>` | | | `notFoundValue` | `null` | | | `flags` | `[InjectFlags](../injectflags)` | Optional. Default is `undefined`. | Returns `T | null` | | get() | | --- | | `get<T>(token: ProviderToken<T>, notFoundValue?: T, flags?: InjectFlags): any` **Deprecated** from v9.0.0 use TestBed.inject Parameters | | | | | --- | --- | --- | | `token` | `[ProviderToken](../providertoken)<T>` | | | `notFoundValue` | `T` | Optional. Default is `undefined`. | | `flags` | `[InjectFlags](../injectflags)` | Optional. Default is `undefined`. | Returns `any` | | `get(token: any, notFoundValue?: any): any` **Deprecated** from v9.0.0 use TestBed.inject Parameters | | | | | --- | --- | --- | | `token` | `any` | | | `notFoundValue` | `any` | Optional. Default is `undefined`. | Returns `any` | | runInInjectionContext() | | --- | | Runs the given function in the `[EnvironmentInjector](../environmentinjector)` context of `[TestBed](testbed)`. See also:* EnvironmentInjector#runInContext | | `runInInjectionContext<T>(fn: () => T): T` Parameters | | | | | --- | --- | --- | | `fn` | `() => T` | | Returns `T` | | execute() | | --- | | `execute(tokens: any[], fn: Function, context?: any): any` Parameters | | | | | --- | --- | --- | | `tokens` | `any[]` | | | `fn` | `Function` | | | `context` | `any` | Optional. Default is `undefined`. | Returns `any` | | overrideModule() | | --- | | `overrideModule(ngModule: Type<any>, override: MetadataOverride<NgModule>): TestBed` Parameters | | | | | --- | --- | --- | | `ngModule` | `[Type](../type)<any>` | | | `override` | `[MetadataOverride](metadataoverride)<[NgModule](../ngmodule)>` | | Returns `[TestBed](testbed)` | | overrideComponent() | | --- | | `overrideComponent(component: Type<any>, override: MetadataOverride<Component>): TestBed` Parameters | | | | | --- | --- | --- | | `component` | `[Type](../type)<any>` | | | `override` | `[MetadataOverride](metadataoverride)<[Component](../component)>` | | Returns `[TestBed](testbed)` | | overrideDirective() | | --- | | `overrideDirective(directive: Type<any>, override: MetadataOverride<Directive>): TestBed` Parameters | | | | | --- | --- | --- | | `directive` | `[Type](../type)<any>` | | | `override` | `[MetadataOverride](metadataoverride)<[Directive](../directive)>` | | Returns `[TestBed](testbed)` | | overridePipe() | | --- | | `overridePipe(pipe: Type<any>, override: MetadataOverride<Pipe>): TestBed` Parameters | | | | | --- | --- | --- | | `pipe` | `[Type](../type)<any>` | | | `override` | `[MetadataOverride](metadataoverride)<[Pipe](../pipe)>` | | Returns `[TestBed](testbed)` | | overrideTemplate() | | --- | | `overrideTemplate(component: Type<any>, template: string): TestBed` Parameters | | | | | --- | --- | --- | | `component` | `[Type](../type)<any>` | | | `template` | `string` | | Returns `[TestBed](testbed)` | | overrideProvider() | | --- | | Overwrites all providers for the given token with the given provider definition. | | `overrideProvider(token: any, provider: { useFactory: Function; deps: any[]; multi?: boolean; }): TestBed` Parameters | | | | | --- | --- | --- | | `token` | `any` | | | `provider` | `object` | | Returns `[TestBed](testbed)` | | `overrideProvider(token: any, provider: { useValue: any; multi?: boolean; }): TestBed` Parameters | | | | | --- | --- | --- | | `token` | `any` | | | `provider` | `object` | | Returns `[TestBed](testbed)` | | `overrideProvider(token: any, provider: { useFactory?: Function; useValue?: any; deps?: any[]; multi?: boolean; }): TestBed` Parameters | | | | | --- | --- | --- | | `token` | `any` | | | `provider` | `object` | | Returns `[TestBed](testbed)` | | overrideTemplateUsingTestingModule() | | --- | | `overrideTemplateUsingTestingModule(component: Type<any>, template: string): TestBed` Parameters | | | | | --- | --- | --- | | `component` | `[Type](../type)<any>` | | | `template` | `string` | | Returns `[TestBed](testbed)` | | createComponent() | | --- | | `createComponent<T>(component: Type<T>): ComponentFixture<T>` Parameters | | | | | --- | --- | --- | | `component` | `[Type<T>](../type)` | | Returns `[ComponentFixture<T>](componentfixture)` | angular waitForAsync waitForAsync ============ `function` Wraps a test function in an asynchronous test zone. The test will automatically complete when all asynchronous calls within this zone are done. Can be used to wrap an [`inject`](inject) call. [See more...](waitforasync#description) ### `waitForAsync(fn: Function): (done: any) => any` ###### Parameters | | | | | --- | --- | --- | | `fn` | `Function` | | ###### Returns `(done: any) => any` Description ----------- Example: ``` it('...', waitForAsync(inject([AClass], (object) => { object.doSomething.then(() => { expect(...); }) }); ``` angular flush flush ===== `function` Flushes any pending microtasks and simulates the asynchronous passage of time for the timers in the `[fakeAsync](fakeasync)` zone by draining the macrotask queue until it is empty. ### `flush(maxTurns?: number): number` ###### Parameters | | | | | --- | --- | --- | | `maxTurns` | `number` | The maximum number of times the scheduler attempts to clear its queue before throwing an error. Optional. Default is `undefined`. | ###### Returns `number`: The simulated time elapsed, in milliseconds. angular TestModuleMetadata TestModuleMetadata ================== `interface` ``` interface TestModuleMetadata { providers?: any[] declarations?: any[] imports?: any[] schemas?: Array<SchemaMetadata | any[]> teardown?: ModuleTeardownOptions errorOnUnknownElements?: boolean errorOnUnknownProperties?: boolean } ``` Properties ---------- | Property | Description | | --- | --- | | `providers?: any[]` | | | `declarations?: any[]` | | | `imports?: any[]` | | | `schemas?: Array<[SchemaMetadata](../schemametadata) | any[]>` | | | `teardown?: [ModuleTeardownOptions](moduleteardownoptions)` | | | `errorOnUnknownElements?: boolean` | Whether NG0304 runtime errors should be thrown when unknown elements are present in component's template. Defaults to `false`, where the error is simply logged. If set to `true`, the error is thrown. See also:* <https://angular.io/errors/NG8001> for the description of the problem and how to fix it | | `errorOnUnknownProperties?: boolean` | Whether errors should be thrown when unknown properties are present in component's template. Defaults to `false`, where the error is simply logged. If set to `true`, the error is thrown. See also:* <https://angular.io/errors/NG8002> for the description of the error and how to fix it | angular InjectSetupWrapper InjectSetupWrapper ================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` ``` class InjectSetupWrapper { constructor(_moduleDef: () => TestModuleMetadata) inject(tokens: any[], fn: Function): () => any } ``` Constructor ----------- | | | | | | --- | --- | --- | --- | | `constructor(_moduleDef: () => TestModuleMetadata)` Parameters | | | | | --- | --- | --- | | `_moduleDef` | `() => [TestModuleMetadata](testmodulemetadata)` | | | Methods ------- | inject() | | --- | | `inject(tokens: any[], fn: Function): () => any` Parameters | | | | | --- | --- | --- | | `tokens` | `any[]` | | | `fn` | `Function` | | Returns `() => any` | angular withModule withModule ========== `function` ### `withModule(moduleDef: TestModuleMetadata): InjectSetupWrapper` ###### Parameters | | | | | --- | --- | --- | | `moduleDef` | `[TestModuleMetadata](testmodulemetadata)` | | ###### Returns `[InjectSetupWrapper](injectsetupwrapper)` ### `withModule(moduleDef: TestModuleMetadata, fn: Function): () => any` ###### Parameters | | | | | --- | --- | --- | | `moduleDef` | `[TestModuleMetadata](testmodulemetadata)` | | | `fn` | `Function` | | ###### Returns `() => any` angular ModuleTeardownOptions ModuleTeardownOptions ===================== `interface` Configures the test module teardown behavior in `[TestBed](testbed)`. ``` interface ModuleTeardownOptions { destroyAfterEach: boolean rethrowErrors?: boolean } ``` Properties ---------- | Property | Description | | --- | --- | | `destroyAfterEach: boolean` | Whether the test module should be destroyed after every test. Defaults to `true`. | | `rethrowErrors?: boolean` | Whether errors during test module destruction should be re-thrown. Defaults to `true`. | angular ComponentFixture ComponentFixture ================ `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Fixture for debugging and testing a component. ``` class ComponentFixture<T> { constructor(componentRef: ComponentRef<T>, ngZone: NgZone, _autoDetect: boolean) debugElement: DebugElement componentInstance: T nativeElement: any elementRef: ElementRef changeDetectorRef: ChangeDetectorRef componentRef: ComponentRef<T> ngZone: NgZone | null detectChanges(checkNoChanges: boolean = true): void checkNoChanges(): void autoDetectChanges(autoDetect: boolean = true) isStable(): boolean whenStable(): Promise<any> whenRenderingDone(): Promise<any> destroy(): void } ``` Constructor ----------- | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `constructor(componentRef: ComponentRef<T>, ngZone: NgZone, _autoDetect: boolean)` Parameters | | | | | --- | --- | --- | | `componentRef` | `[ComponentRef](../componentref)<T>` | | | `ngZone` | `[NgZone](../ngzone)` | | | `_autoDetect` | `boolean` | | | Properties ---------- | Property | Description | | --- | --- | | `debugElement: [DebugElement](../debugelement)` | The DebugElement associated with the root element of this component. | | `componentInstance: T` | The instance of the root component class. | | `nativeElement: any` | The native element at the root of the component. | | `elementRef: [ElementRef](../elementref)` | The ElementRef for the element at the root of the component. | | `changeDetectorRef: [ChangeDetectorRef](../changedetectorref)` | The ChangeDetectorRef for the component | | `componentRef: [ComponentRef](../componentref)<T>` | Declared in Constructor | | `ngZone: [NgZone](../ngzone) | null` | Declared in Constructor | Methods ------- | detectChanges() | | --- | | Trigger a change detection cycle for the component. | | `detectChanges(checkNoChanges: boolean = true): void` Parameters | | | | | --- | --- | --- | | `checkNoChanges` | `boolean` | Optional. Default is `true`. | Returns `void` | | checkNoChanges() | | --- | | Do a change detection run to make sure there were no changes. | | `checkNoChanges(): void` Parameters There are no parameters. Returns `void` | | autoDetectChanges() | | --- | | Set whether the fixture should autodetect changes. | | `autoDetectChanges(autoDetect: boolean = true)` Parameters | | | | | --- | --- | --- | | `autoDetect` | `boolean` | Optional. Default is `true`. | | | Also runs detectChanges once so that any existing change is detected. | | isStable() | | --- | | Return whether the fixture is currently stable or has async tasks that have not been completed yet. | | `isStable(): boolean` Parameters There are no parameters. Returns `boolean` | | whenStable() | | --- | | Get a promise that resolves when the fixture is stable. | | `whenStable(): Promise<any>` Parameters There are no parameters. Returns `Promise<any>` | | This can be used to resume testing after events have triggered asynchronous activity or asynchronous change detection. | | whenRenderingDone() | | --- | | Get a promise that resolves when the ui state is stable following animations. | | `whenRenderingDone(): Promise<any>` Parameters There are no parameters. Returns `Promise<any>` | | destroy() | | --- | | Trigger component destruction. | | `destroy(): void` Parameters There are no parameters. Returns `void` | angular getTestBed getTestBed ========== `function` Returns a singleton of the `[TestBed](testbed)` class. ### `getTestBed(): TestBed` ###### Parameters There are no parameters. ###### Returns `[TestBed](testbed)` angular TestBedStatic TestBedStatic ============= `interface` Static methods implemented by the `[TestBed](testbed)`. ``` interface TestBedStatic extends TestBed { new (...args: any[]): TestBed // inherited from core/testing/TestBed platform: PlatformRef ngModule: Type<any> | Type<any>[] initTestEnvironment(ngModule: Type<any> | Type<any>[], platform: PlatformRef, options?: TestEnvironmentOptions): void resetTestEnvironment(): void resetTestingModule(): TestBed configureCompiler(config: { providers?: any[]; useJit?: boolean; }): void configureTestingModule(moduleDef: TestModuleMetadata): TestBed compileComponents(): Promise<any> inject<T>(token: ProviderToken<T>, notFoundValue: undefined, options: InjectOptions & { optional?: false; }): T get<T>(token: ProviderToken<T>, notFoundValue?: T, flags?: InjectFlags): any runInInjectionContext<T>(fn: () => T): T execute(tokens: any[], fn: Function, context?: any): any overrideModule(ngModule: Type<any>, override: MetadataOverride<NgModule>): TestBed overrideComponent(component: Type<any>, override: MetadataOverride<Component>): TestBed overrideDirective(directive: Type<any>, override: MetadataOverride<Directive>): TestBed overridePipe(pipe: Type<any>, override: MetadataOverride<Pipe>): TestBed overrideTemplate(component: Type<any>, template: string): TestBed overrideProvider(token: any, provider: { useFactory: Function; deps: any[]; multi?: boolean; }): TestBed overrideTemplateUsingTestingModule(component: Type<any>, template: string): TestBed createComponent<T>(component: Type<T>): ComponentFixture<T> } ``` Methods ------- | *construct signature* | | --- | | `new (...args: any[]): TestBed` Parameters | | | | | --- | --- | --- | | `args` | `any[]` | | Returns `[TestBed](testbed)` | angular fakeAsync fakeAsync ========= `function` Wraps a function to be executed in the `[fakeAsync](fakeasync)` zone: * Microtasks are manually executed by calling `[flushMicrotasks](flushmicrotasks)()`. * Timers are synchronous; `<tick>()` simulates the asynchronous passage of time. [See more...](fakeasync#description) ### `fakeAsync(fn: Function): (...args: any[]) => any` ###### Parameters | | | | | --- | --- | --- | | `fn` | `Function` | The function that you want to wrap in the `fakeAysnc` zone. | ###### Returns `(...args: any[]) => any`: The function wrapped to be executed in the `[fakeAsync](fakeasync)` zone. Any arguments passed when calling this returned function will be passed through to the `fn` function in the parameters when it is called. Description ----------- If there are any pending timers at the end of the function, an exception is thrown. Can be used to wrap `inject()` calls. Further information is available in the [Usage Notes...](fakeasync#usage-notes) Usage notes ----------- ### Example ``` describe('this test', () => { it('looks async but is synchronous', <any>fakeAsync((): void => { let flag = false; setTimeout(() => { flag = true; }, 100); expect(flag).toBe(false); tick(50); expect(flag).toBe(false); tick(50); expect(flag).toBe(true); })); }); ```
programming_docs
angular TestComponentRenderer TestComponentRenderer ===================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An abstract class for inserting the root test component element in a platform independent way. ``` class TestComponentRenderer { insertRootElement(rootElementId: string) removeAllRootElements()? } ``` Provided in ----------- * [``` BrowserDynamicTestingModule ```](../../platform-browser-dynamic/testing/browserdynamictestingmodule) Methods ------- | insertRootElement() | | --- | | `insertRootElement(rootElementId: string)` Parameters | | | | | --- | --- | --- | | `rootElementId` | `string` | | | | removeAllRootElements() | | --- | | `removeAllRootElements()?` Parameters There are no parameters. | angular resetFakeAsyncZone resetFakeAsyncZone ================== `function` Clears out the shared fake async zone for a test. To be called in a global `beforeEach`. ### `resetFakeAsyncZone(): void` ###### Parameters There are no parameters. ###### Returns `void` angular ng.getComponent ng.getComponent =============== `global` `function` Retrieves the component instance associated with a given DOM element. ### `ng.getComponent<T>(element: Element): T | null` ###### Parameters | | | | | --- | --- | --- | | `element` | `Element` | DOM element from which the component should be retrieved. | ###### Returns `T | null`: Component instance associated with the element or `null` if there is no component associated with it. Usage notes ----------- Given the following DOM structure: ``` <app-root> <div> <child-comp></child-comp> </div> </app-root> ``` Calling `[getComponent](nggetcomponent)` on `<child-comp>` will return the instance of `ChildComponent` associated with this DOM element. Calling the function on `<app-root>` will return the `MyApp` instance. angular ng.getDirectives ng.getDirectives ================ `global` `function` Retrieves directive instances associated with a given DOM node. Does not include component instances. ### `ng.getDirectives(node: Node): {}[]` ###### Parameters | | | | | --- | --- | --- | | `node` | `Node` | DOM node for which to get the directives. | ###### Returns `{}[]`: Array of directives associated with the node. Usage notes ----------- Given the following DOM structure: ``` <app-root> <button my-button></button> <my-comp></my-comp> </app-root> ``` Calling `[getDirectives](nggetdirectives)` on `<button>` will return an array with an instance of the `MyButton` directive that is associated with the DOM node. Calling `[getDirectives](nggetdirectives)` on `<my-comp>` will return an empty array. angular ng.getInjector ng.getInjector ============== `global` `function` Retrieves an `[Injector](../injector)` associated with an element, component or directive instance. ### `ng.getInjector(elementOrDir: {} | Element): Injector` ###### Parameters | | | | | --- | --- | --- | | `elementOrDir` | `{} | Element` | DOM element, component or directive instance for which to retrieve the injector. | ###### Returns `[Injector](../injector)`: Injector associated with the element, component or directive instance. angular ComponentDebugMetadata ComponentDebugMetadata ====================== `interface` Partial metadata for a given component instance. This information might be useful for debugging purposes or tooling. Currently the following fields are available: * inputs * outputs * encapsulation * changeDetection ``` interface ComponentDebugMetadata extends DirectiveDebugMetadata { encapsulation: ViewEncapsulation changeDetection: ChangeDetectionStrategy // inherited from core/global/DirectiveDebugMetadata inputs: Record<string, string> outputs: Record<string, string> } ``` Properties ---------- | Property | Description | | --- | --- | | `encapsulation: [ViewEncapsulation](../viewencapsulation)` | | | `changeDetection: [ChangeDetectionStrategy](../changedetectionstrategy)` | | angular ng.getDirectiveMetadata ng.getDirectiveMetadata ======================= `global` `function` Returns the debug (partial) metadata for a particular directive or component instance. The function accepts an instance of a directive or component and returns the corresponding metadata. ### `ng.getDirectiveMetadata(directiveOrComponentInstance: any): ComponentDebugMetadata | DirectiveDebugMetadata | null` ###### Parameters | | | | | --- | --- | --- | | `directiveOrComponentInstance` | `any` | Instance of a directive or component | ###### Returns `[ComponentDebugMetadata](componentdebugmetadata) | [DirectiveDebugMetadata](directivedebugmetadata) | null`: metadata of the passed directive or component angular ng.getHostElement ng.getHostElement ================= `global` `function` Retrieves the host element of a component or directive instance. The host element is the DOM element that matched the selector of the directive. ### `ng.getHostElement(componentOrDirective: {}): Element` ###### Parameters | | | | | --- | --- | --- | | `componentOrDirective` | `{}` | Component or directive instance for which the host element should be retrieved. | ###### Returns `Element`: Host element of the target. angular ng.getListeners ng.getListeners =============== `global` `function` Retrieves a list of event listeners associated with a DOM element. The list does include host listeners, but it does not include event listeners defined outside of the Angular context (e.g. through `addEventListener`). ### `ng.getListeners(element: Element): Listener[]` ###### Parameters | | | | | --- | --- | --- | | `element` | `Element` | Element for which the DOM listeners should be retrieved. | ###### Returns `[Listener](listener)[]`: Array of event listeners on the DOM element. Usage notes ----------- Given the following DOM structure: ``` <app-root> <div (click)="doSomething()"></div> </app-root> ``` Calling `[getListeners](nggetlisteners)` on `<div>` will return an object that looks as follows: ``` { name: 'click', element: <div>, callback: () => doSomething(), useCapture: false } ``` angular ng.getOwningComponent ng.getOwningComponent ===================== `global` `function` Retrieves the component instance whose view contains the DOM element. [See more...](nggetowningcomponent#description) ### `ng.getOwningComponent<T>(elementOrDir: {} | Element): T | null` ###### Parameters | | | | | --- | --- | --- | | `elementOrDir` | `{} | Element` | DOM element, component or directive instance for which to retrieve the root components. | ###### Returns `T | null`: Component instance whose view owns the DOM element or null if the element is not part of a component view. Description ----------- For example, if `<child-comp>` is used in the template of `<app-comp>` (i.e. a `[ViewChild](../viewchild)` of `<app-comp>`), calling `[getOwningComponent](nggetowningcomponent)` on `<child-comp>` would return `<app-comp>`. angular ng.getContext ng.getContext ============= `global` `function` If inside an embedded view (e.g. `*[ngIf](../../common/ngif)` or `*[ngFor](../../common/ngfor)`), retrieves the context of the embedded view that the element is part of. Otherwise retrieves the instance of the component whose view owns the element (in this case, the result is the same as calling `[getOwningComponent](nggetowningcomponent)`). ### `ng.getContext<T extends {}>(element: Element): T | null` ###### Parameters | | | | | --- | --- | --- | | `element` | `Element` | Element for which to get the surrounding component instance. | ###### Returns `T | null`: Instance of the component that is around the element or null if the element isn't inside any component. angular DirectiveDebugMetadata DirectiveDebugMetadata ====================== `interface` Partial metadata for a given directive instance. This information might be useful for debugging purposes or tooling. Currently only `inputs` and `outputs` metadata is available. ``` interface DirectiveDebugMetadata { inputs: Record<string, string> outputs: Record<string, string> } ``` Child interfaces ---------------- * `[ComponentDebugMetadata](componentdebugmetadata)` Properties ---------- | Property | Description | | --- | --- | | `inputs: Record<string, string>` | | | `outputs: Record<string, string>` | | angular Listener Listener ======== `interface` Event listener configuration returned from `[getListeners](nggetlisteners)`. ``` interface Listener { name: string element: Element callback: (value: any) => any useCapture: boolean type: 'dom' | 'output' } ``` Properties ---------- | Property | Description | | --- | --- | | `name: string` | Name of the event listener. | | `element: Element` | Element that the listener is bound to. | | `callback: (value: any) => any` | Callback that is invoked when the event is triggered. | | `useCapture: boolean` | Whether the listener is using event capturing. | | `type: 'dom' | 'output'` | Type of the listener (e.g. a native DOM event or a custom @Output). | angular ng.getRootComponents ng.getRootComponents ==================== `global` `function` Retrieves all root components associated with a DOM element, directive or component instance. Root components are those which have been bootstrapped by Angular. ### `ng.getRootComponents(elementOrDir: {} | Element): {}[]` ###### Parameters | | | | | --- | --- | --- | | `elementOrDir` | `{} | Element` | DOM element, component or directive instance for which to retrieve the root components. | ###### Returns `{}[]`: Root components associated with the target object. angular ng.applyChanges ng.applyChanges =============== `global` `function` Marks a component for check (in case of OnPush components) and synchronously performs change detection on the application this component belongs to. ### `ng.applyChanges(component: {}): void` ###### Parameters | | | | | --- | --- | --- | | `component` | `{}` | Component to [mark for check](../changedetectorref#markForCheck). | ###### Returns `void` angular @angular/platform-server/init @angular/platform-server/init ============================= `entry-point` Initializes the server environment for rendering an Angular application. For example, it provides shims (such as DOM globals) for the server environment. The initialization happens as a [side effect of importing](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#import_a_module_for_its_side_effects_only) the entry point (i.e. there are no specific exports): ``` import '@angular/platform-server/init'; ``` > The import must come before any imports (direct or transitive) that rely on DOM built-ins being available. > > Entry point exports ------------------- *No public exports.* angular BEFORE_APP_SERIALIZED BEFORE\_APP\_SERIALIZED ======================= `const` A function that will be executed when calling `[renderApplication](renderapplication)`, `[renderModuleFactory](rendermodulefactory)` or `[renderModule](rendermodule)` just before current platform state is rendered to string. ### `const BEFORE_APP_SERIALIZED: InjectionToken<(() => void | Promise<void>)[]>;` angular ServerModule ServerModule ============ `ngmodule` The ng module for the server. ``` class ServerModule { } ``` Providers --------- | Provider | | --- | | ``` TRANSFER_STATE_SERIALIZATION_PROVIDERS ``` | | ``` SERVER_RENDER_PROVIDERS ``` | | ``` SERVER_HTTP_PROVIDERS ``` | | ``` { provide: Testability, useValue: null } ``` | | ``` { provide: TESTABILITY, useValue: null } ``` | | ``` { provide: ViewportScroller, useClass: NullViewportScroller } ``` | angular PlatformState PlatformState ============= `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Representation of the current platform state. ``` class PlatformState { renderToString(): string getDocument(): any } ``` Methods ------- | renderToString() | | --- | | Renders the current state of the platform to string. | | `renderToString(): string` Parameters There are no parameters. Returns `string` | | getDocument() | | --- | | Returns the current DOM state. | | `getDocument(): any` Parameters There are no parameters. Returns `any` | angular INITIAL_CONFIG INITIAL\_CONFIG =============== `const` The DI token for setting the initial config for the platform. ### `const INITIAL_CONFIG: InjectionToken<PlatformConfig>;` angular renderModuleFactory renderModuleFactory =================== `function` `deprecated` Bootstraps an application using provided [`NgModuleFactory`](../core/ngmodulefactory) and serializes the page content to string. **Deprecated:** This symbol is no longer necessary as of Angular v13. Use [`renderModule`](rendermodule) API instead. ### `renderModuleFactory<T>(moduleFactory: NgModuleFactory<T>, options: { document?: string; url?: string; extraProviders?: StaticProvider[]; }): Promise<string>` **Deprecated** This symbol is no longer necessary as of Angular v13. Use [`renderModule`](rendermodule) API instead. ###### Parameters | | | | | --- | --- | --- | | `moduleFactory` | `[NgModuleFactory<T>](../core/ngmodulefactory)` | An instance of the [`NgModuleFactory`](../core/ngmodulefactory) that should be used for bootstrap. | | `options` | `object` | Additional configuration for the render operation:* `document` - the document of the page to render, either as an HTML string or as a reference to the `document` instance. * `url` - the URL for the current render request. * `extraProviders` - set of platform level providers for the current render request. | ###### Returns `Promise<string>` angular renderModule renderModule ============ `function` Bootstraps an application using provided NgModule and serializes the page content to string. ### `renderModule<T>(moduleType: Type<T>, options: { document?: string | Document; url?: string; extraProviders?: StaticProvider[]; }): Promise<string>` ###### Parameters | | | | | --- | --- | --- | | `moduleType` | `[Type<T>](../core/type)` | A reference to an NgModule that should be used for bootstrap. | | `options` | `object` | Additional configuration for the render operation:* `document` - the document of the page to render, either as an HTML string or as a reference to the `document` instance. * `url` - the URL for the current render request. * `extraProviders` - set of platform level providers for the current render request. | ###### Returns `Promise<string>` angular platformDynamicServer platformDynamicServer ===================== `const` The server platform that supports the runtime compiler. ### `const platformDynamicServer: (extraProviders?: StaticProvider[]) => PlatformRef;` angular ServerTransferStateModule ServerTransferStateModule ========================= `ngmodule` `deprecated` NgModule to install on the server side while using the `[TransferState](../platform-browser/transferstate)` to transfer state from server to client. [See more...](servertransferstatemodule#description) **Deprecated:** no longer needed, you can inject the `[TransferState](../platform-browser/transferstate)` in an app without providing this module. ``` class ServerTransferStateModule { } ``` Description ----------- Note: this module is not needed if the `[renderApplication](renderapplication)` function is used. The `[renderApplication](renderapplication)` makes all providers from this module available in the application. angular platformServer platformServer ============== `const` ### `const platformServer: (extraProviders?: StaticProvider[]) => PlatformRef;` angular renderApplication renderApplication ================= `function` `[developer preview](../../guide/releases#developer-preview)` Bootstraps an instance of an Angular application and renders it to a string. [See more...](renderapplication#description) ### `renderApplication<T>(rootComponent: Type<T>, options: { appId: string; document?: string | Document; url?: string; providers?: (Provider | EnvironmentProviders)[]; platformProviders?: Provider[]; }): Promise<string>` ###### Parameters | | | | | --- | --- | --- | | `rootComponent` | `[Type<T>](../core/type)` | A reference to a Standalone Component that should be rendered. | | `options` | `object` | Additional configuration for the render operation:* `appId` - a string identifier of this application. The appId is used to prefix all server-generated stylings and state keys of the application in TransferState use-cases. * `document` - the document of the page to render, either as an HTML string or as a reference to the `document` instance. * `url` - the URL for the current render request. * `providers` - set of application level providers for the current render request. * `platformProviders` - the platform level providers for the current render request. | ###### Returns `Promise<string>`: A Promise, that returns serialized (to a string) rendered page, once resolved. Description ----------- Note: the root component passed into this function *must* be a standalone one (should have the `standalone: true` flag in the `@[Component](../core/component)` decorator config). ``` @Component({ standalone: true, template: 'Hello world!' }) class RootComponent {} const output: string = await renderApplication(RootComponent, {appId: 'server-app'}); ``` angular PlatformConfig PlatformConfig ============== `interface` Config object passed to initialize the platform. ``` interface PlatformConfig { document?: string url?: string useAbsoluteUrl?: boolean baseUrl?: string } ``` Properties ---------- | Property | Description | | --- | --- | | `document?: string` | The initial DOM to use to bootstrap the server application. | | `url?: string` | The URL for the current application state. This is used for initializing the platform's location. `protocol`, `hostname`, and `port` will be overridden if `baseUrl` is set. | | `useAbsoluteUrl?: boolean` | Whether to append the absolute URL to any relative HTTP requests. If set to true, this logic executes prior to any HTTP interceptors that may run later on in the request. `baseUrl` must be supplied if this flag is enabled. | | `baseUrl?: string` | The base URL for resolving absolute URL for HTTP requests. It must be set if `useAbsoluteUrl` is true, and must consist of protocol, hostname, and optional port. This option has no effect if `useAbsoluteUrl` is not enabled. | angular @angular/platform-server/testing @angular/platform-server/testing ================================ `entry-point` Supplies a testing module for the Angular platform server subsystem. Entry point exports ------------------- ### NgModules | | | | --- | --- | | `[ServerTestingModule](testing/servertestingmodule)` | NgModule for testing. | ### Types | | | | --- | --- | | `[platformServerTesting](testing/platformservertesting)` | Platform for testing | angular ServerTestingModule ServerTestingModule =================== `ngmodule` NgModule for testing. ``` class ServerTestingModule { } ``` Providers --------- | Provider | | --- | | ``` SERVER_RENDER_PROVIDERS ``` | angular platformServerTesting platformServerTesting ===================== `const` Platform for testing ### `const platformServerTesting: (extraProviders?: StaticProvider[]) => PlatformRef;` angular @angular/localize/init @angular/localize/init ====================== `entry-point` The `@angular/localize` package exposes the `[$localize](init/%24localize)` function in the global namespace, which can be used to tag i18n messages in your code that needs to be translated. Entry point exports ------------------- ### Types | | | | --- | --- | | `[$localize](init/%24localize)` | Tag a template literal string for localization. |
programming_docs
angular loadTranslations loadTranslations ================ `function` Load translations for use by `[$localize](init/%24localize)`, if doing runtime translation. [See more...](loadtranslations#description) ### `loadTranslations(translations: Record<string, string>)` ###### Parameters | | | | | --- | --- | --- | | `translations` | `Record<string, string>` | A map from message ID to translated message. These messages are processed and added to a lookup based on their `[MessageId](messageid)`. | See also -------- * `[clearTranslations](cleartranslations)()` for removing translations loaded using this function. * `[$localize](init/%24localize)` for tagging messages as needing to be translated. Description ----------- If the `[$localize](init/%24localize)` tagged strings are not going to be replaced at compiled time, it is possible to load a set of translations that will be applied to the `[$localize](init/%24localize)` tagged strings at runtime, in the browser. Loading a new translation will overwrite a previous translation if it has the same `[MessageId](messageid)`. Note that `[$localize](init/%24localize)` messages are only processed once, when the tagged string is first encountered, and does not provide dynamic language changing without refreshing the browser. Loading new translations later in the application life-cycle will not change the translated text of messages that have already been translated. The message IDs and translations are in the same format as that rendered to "simple JSON" translation files when extracting messages. In particular, placeholders in messages are rendered using the `{$PLACEHOLDER_NAME}` syntax. For example the message from the following template: ``` <div i18n>pre<span>inner-pre<b>bold</b>inner-post</span>post</div> ``` would have the following form in the `translations` map: ``` { "2932901491976224757": "pre{$START_TAG_SPAN}inner-pre{$START_BOLD_TEXT}bold{$CLOSE_BOLD_TEXT}inner-post{$CLOSE_TAG_SPAN}post" } ``` angular MessageId MessageId ========= `type-alias` A string that uniquely identifies a message, to be used for matching translations. ``` type MessageId = string; ``` angular clearTranslations clearTranslations ================= `function` Remove all translations for `[$localize](init/%24localize)`, if doing runtime translation. [See more...](cleartranslations#description) ### `clearTranslations()` ###### Parameters There are no parameters. See also -------- * `[loadTranslations](loadtranslations)()` for loading translations at runtime. * `[$localize](init/%24localize)` for tagging messages as needing to be translated. Description ----------- All translations that had been loading into memory using `[loadTranslations](loadtranslations)()` will be removed. angular TargetMessage TargetMessage ============= `type-alias` A string containing a translation target message. [See more...](targetmessage#description) ``` type TargetMessage = string; ``` Description ----------- I.E. the message that indicates what will be translated to. Uses `{$placeholder-name}` to indicate a placeholder. angular $localize $localize ========= `global` `const` Tag a template literal string for localization. [See more...](%24localize#description) ### `const $localize: LocalizeFn;` #### Description For example: ``` $localize `some string to localize` ``` **Providing meaning, description and id** You can optionally specify one or more of `meaning`, `description` and `id` for a localized string by pre-pending it with a colon delimited block of the form: ``` $localize`:meaning|description@@id:source message text`; $localize`:meaning|:source message text`; $localize`:description:source message text`; $localize`:@@id:source message text`; ``` This format is the same as that used for `i18n` markers in Angular templates. See the [Angular i18n guide](../../../guide/i18n-common-prepare#mark-text-in-component-template). **Naming placeholders** If the template literal string contains expressions, then the expressions will be automatically associated with placeholder names for you. For example: ``` $localize `Hi ${name}! There are ${items.length} items.`; ``` will generate a message-source of `Hi {$PH}! There are {$PH_1} items`. The recommended practice is to name the placeholder associated with each expression though. Do this by providing the placeholder name wrapped in `:` characters directly after the expression. These placeholder names are stripped out of the rendered localized string. For example, to name the `items.length` expression placeholder `itemCount` you write: ``` $localize `There are ${items.length}:itemCount: items`; ``` **Escaping colon markers** If you need to use a `:` character directly at the start of a tagged string that has no metadata block, or directly after a substitution expression that has no name you must escape the `:` by preceding it with a backslash: For example: ``` // message has a metadata block so no need to escape colon $localize `:some description::this message starts with a colon (:)`; // no metadata block so the colon must be escaped $localize `\:this message starts with a colon (:)`; ``` ``` // named substitution so no need to escape colon $localize `${label}:label:: ${}` // anonymous substitution so colon must be escaped $localize `${label}\: ${}` ``` **Processing localized strings:** There are three scenarios: * **compile-time inlining**: the `[$localize](%24localize)` tag is transformed at compile time by a transpiler, removing the tag and replacing the template literal string with a translated literal string from a collection of translations provided to the transpilation tool. * **run-time evaluation**: the `[$localize](%24localize)` tag is a run-time function that replaces and reorders the parts (static strings and expressions) of the template literal string with strings from a collection of translations loaded at run-time. * **pass-through evaluation**: the `[$localize](%24localize)` tag is a run-time function that simply evaluates the original template literal string without applying any translations to the parts. This version is used during development or where there is no need to translate the localized template literals. angular provideCloudflareLoader provideCloudflareLoader ======================= `const` Function that generates an ImageLoader for [Cloudflare Image Resizing](https://developers.cloudflare.com/images/image-resizing/) and turns it into an Angular provider. Note: Cloudflare has multiple image products - this provider is specifically for Cloudflare Image Resizing; it will not work with Cloudflare Images or Cloudflare Polish. ### `const provideCloudflareLoader: (path: string) => Provider[];` angular IMAGE_LOADER IMAGE\_LOADER ============= `const` Injection token that configures the image loader function. ### `const IMAGE_LOADER: InjectionToken<ImageLoader>;` #### See also * `[ImageLoader](imageloader)` * `[NgOptimizedImage](ngoptimizedimage)` angular isPlatformWorkerUi isPlatformWorkerUi ================== `function` Returns whether a platform id represents a web worker UI platform. ### `isPlatformWorkerUi(platformId: Object): boolean` ###### Parameters | | | | | --- | --- | --- | | `platformId` | `Object` | | ###### Returns `boolean` angular getLocaleNumberSymbol getLocaleNumberSymbol ===================== `function` Retrieves a localized number symbol that can be used to replace placeholders in number formats. ### `getLocaleNumberSymbol(locale: string, symbol: NumberSymbol): string` ###### Parameters | | | | | --- | --- | --- | | `locale` | `string` | The locale code. | | `symbol` | `[NumberSymbol](numbersymbol)` | The symbol to localize. | ###### Returns `string`: The character for the localized symbol. See also -------- * `[NumberSymbol](numbersymbol)` * [Internationalization (i18n) Guide](../../guide/i18n-overview) angular formatNumber formatNumber ============ `function` Formats a number as text, with group sizing, separator, and other parameters based on the locale. ### `formatNumber(value: number, locale: string, digitsInfo?: string): string` ###### Parameters | | | | | --- | --- | --- | | `value` | `number` | The number to format. | | `locale` | `string` | A locale code for the locale format rules to use. | | `digitsInfo` | `string` | Decimal representation options, specified by a string in the following format: `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `[DecimalPipe](decimalpipe)` for more details. Optional. Default is `undefined`. | ###### Returns `string`: The formatted text string. See also -------- * [Internationalization (i18n) Guide](../../guide/i18n-overview) angular NgForOfContext NgForOfContext ============== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` ``` class NgForOfContext<T, U extends NgIterable<T> = NgIterable<T>> { constructor($implicit: T, ngForOf: U, index: number, count: number) $implicit: T ngForOf: U index: number count: number first: boolean last: boolean even: boolean odd: boolean } ``` Constructor ----------- | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `constructor($implicit: T, ngForOf: U, index: number, count: number)` Parameters | | | | | --- | --- | --- | | `$implicit` | `T` | | | `[ngForOf](ngforof)` | `U` | | | `index` | `number` | | | `count` | `number` | | | Properties ---------- | Property | Description | | --- | --- | | `$implicit: T` | Declared in Constructor | | `[ngForOf](ngforof): U` | Declared in Constructor | | `index: number` | Declared in Constructor | | `count: number` | Declared in Constructor | | `first: boolean` | Read-Only | | `last: boolean` | Read-Only | | `even: boolean` | Read-Only | | `odd: boolean` | Read-Only | angular getLocaleFirstDayOfWeek getLocaleFirstDayOfWeek ======================= `function` Retrieves the first day of the week for the given locale. ### `getLocaleFirstDayOfWeek(locale: string): WeekDay` ###### Parameters | | | | | --- | --- | --- | | `locale` | `string` | A locale code for the locale format rules to use. | ###### Returns `[WeekDay](weekday)`: A day index number, using the 0-based week-day index for `en-US` (Sunday = 0, Monday = 1, ...). For example, for `fr-FR`, returns 1 to indicate that the first day is Monday. See also -------- * [Internationalization (i18n) Guide](../../guide/i18n-overview) angular getLocaleCurrencySymbol getLocaleCurrencySymbol ======================= `function` Retrieves the symbol used to represent the currency for the main country corresponding to a given locale. For example, '$' for `en-US`. ### `getLocaleCurrencySymbol(locale: string): string | null` ###### Parameters | | | | | --- | --- | --- | | `locale` | `string` | A locale code for the locale format rules to use. | ###### Returns `string | null`: The localized symbol character, or `null` if the main country cannot be determined. See also -------- * [Internationalization (i18n) Guide](../../guide/i18n-overview) angular DATE_PIPE_DEFAULT_OPTIONS DATE\_PIPE\_DEFAULT\_OPTIONS ============================ `const` DI token that allows to provide default configuration for the `[DatePipe](datepipe)` instances in an application. The value is an object which can include the following fields: * `dateFormat`: configures the default date format. If not provided, the `[DatePipe](datepipe)` will use the 'mediumDate' as a value. * `timezone`: configures the default timezone. If not provided, the `[DatePipe](datepipe)` will use the end-user's local system timezone. ### `const DATE_PIPE_DEFAULT_OPTIONS: InjectionToken<DatePipeConfig>;` #### See also * `[DatePipeConfig](datepipeconfig)` Usage notes ----------- Various date pipe default values can be overwritten by providing this token with the value that has this interface. For example: Override the default date format by providing a value using the token: ``` providers: [ {provide: DATE_PIPE_DEFAULT_OPTIONS, useValue: {dateFormat: 'shortDate'}} ] ``` Override the default timezone by providing a value using the token: ``` providers: [ {provide: DATE_PIPE_DEFAULT_OPTIONS, useValue: {timezone: '-1200'}} ] ``` angular ImageConfig ImageConfig =========== `type-alias` `[developer preview](../../guide/releases#developer-preview)` A configuration object for the NgOptimizedImage directive. Contains: * breakpoints: An array of integer breakpoints used to generate srcsets for responsive images. [See more...](imageconfig#description) ``` type ImageConfig = { breakpoints?: number[]; }; ``` Description ----------- Learn more about the responsive image configuration in [the NgOptimizedImage guide](../../guide/image-directive). angular FormStyle FormStyle ========= `enum` Context-dependant translation forms for strings. Typically the standalone version is for the nominative form of the word, and the format version is used for the genitive case. See also -------- * [CLDR website](http://cldr.unicode.org/translation/date-time-1/date-time#TOC-Standalone-vs.-Format-Styles) * [Internationalization (i18n) Guide](../../guide/i18n-overview) ``` enum FormStyle { Format Standalone } ``` Members ------- | Member | Description | | --- | --- | | `Format` | | | `Standalone` | | angular Plural Plural ====== `enum` Plurality cases used for translating plurals to different languages. See also -------- * `[NgPlural](ngplural)` * `[NgPluralCase](ngpluralcase)` * [Internationalization (i18n) Guide](../../guide/i18n-overview) ``` enum Plural { Zero: 0 One: 1 Two: 2 Few: 3 Many: 4 Other: 5 } ``` Members ------- | Member | Description | | --- | --- | | `Zero: 0` | | | `One: 1` | | | `Two: 2` | | | `Few: 3` | | | `Many: 4` | | | `Other: 5` | | angular PercentPipe PercentPipe =========== `pipe` Transforms a number to a percentage string, formatted according to locale rules that determine group sizing and separator, decimal-point character, and other locale-specific configurations. ### `{{ value_expression | percent [ : digitsInfo [ : locale ] ] }}` #### Exported from * [``` CommonModule ```](commonmodule) Input value ----------- | | | | | --- | --- | --- | | `value` | `string | number` | The number to be formatted as a percentage. | Parameters ---------- | | | | | --- | --- | --- | | `digitsInfo` | `string` | Decimal representation options, specified by a string in the following format: `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`.* `minIntegerDigits`: The minimum number of integer digits before the decimal point. Default is `1`. * `minFractionDigits`: The minimum number of digits after the decimal point. Default is `0`. * `maxFractionDigits`: The maximum number of digits after the decimal point. Default is `0`. Optional. Default is `undefined`. | | `locale` | `string` | A locale code for the locale format rules to use. When not supplied, uses the value of `[LOCALE\_ID](../core/locale_id)`, which is `en-US` by default. See [Setting your app locale](../../guide/i18n-common-locale-id). Optional. Default is `undefined`. | See also -------- * `[formatPercent](formatpercent)()` Usage notes ----------- The following code shows how the pipe transforms numbers into text strings, according to various format specifications, where the caller's default locale is `en-US`. ``` @Component({ selector: 'percent-pipe', template: `<div> <!--output '26%'--> <p>A: {{a | percent}}</p> <!--output '0,134.950%'--> <p>B: {{b | percent:'4.3-5'}}</p> <!--output '0 134,950 %'--> <p>B: {{b | percent:'4.3-5':'fr'}}</p> </div>` }) export class PercentPipeComponent { a: number = 0.259; b: number = 1.3495; } ``` angular formatDate formatDate ========== `function` Formats a date according to locale rules. ### `formatDate(value: string | number | Date, format: string, locale: string, timezone?: string): string` ###### Parameters | | | | | --- | --- | --- | | `value` | `string | number | Date` | The date to format, as a Date, or a number (milliseconds since UTC epoch) or an [ISO date-time string](https://www.w3.org/TR/NOTE-datetime). | | `format` | `string` | The date-time components to include. See `[DatePipe](datepipe)` for details. | | `locale` | `string` | A locale code for the locale format rules to use. | | `timezone` | `string` | The time zone. A time zone offset from GMT (such as `'+0430'`), or a standard UTC/GMT or continental US time zone abbreviation. If not specified, uses host system settings. Optional. Default is `undefined`. | ###### Returns `string`: The formatted date string. See also -------- * `[DatePipe](datepipe)` * [Internationalization (i18n) Guide](../../guide/i18n-overview) angular HashLocationStrategy HashLocationStrategy ==================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A [`LocationStrategy`](locationstrategy) used to configure the [`Location`](location) service to represent its state in the [hash fragment](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax) of the browser's URL. [See more...](hashlocationstrategy#description) ``` class HashLocationStrategy extends LocationStrategy implements OnDestroy { onPopState(fn: LocationChangeListener): void getBaseHref(): string path(includeHash: boolean = false): string prepareExternalUrl(internal: string): string pushState(state: any, title: string, path: string, queryParams: string) replaceState(state: any, title: string, path: string, queryParams: string) forward(): void back(): void getState(): unknown historyGo(relativePosition: number = 0): void // inherited from common/LocationStrategy abstract path(includeHash?: boolean): string abstract prepareExternalUrl(internal: string): string abstract getState(): unknown abstract pushState(state: any, title: string, url: string, queryParams: string): void abstract replaceState(state: any, title: string, url: string, queryParams: string): void abstract forward(): void abstract back(): void historyGo(relativePosition: number)?: void abstract onPopState(fn: LocationChangeListener): void abstract getBaseHref(): string } ``` Description ----------- For instance, if you call `location.go('/foo')`, the browser's URL will become `example.com#/foo`. Further information is available in the [Usage Notes...](hashlocationstrategy#usage-notes) Methods ------- | onPopState() | | --- | | `onPopState(fn: LocationChangeListener): void` Parameters | | | | | --- | --- | --- | | `fn` | `[LocationChangeListener](locationchangelistener)` | | Returns `void` | | getBaseHref() | | --- | | `getBaseHref(): string` Parameters There are no parameters. Returns `string` | | path() | | --- | | `path(includeHash: boolean = false): string` Parameters | | | | | --- | --- | --- | | `includeHash` | `boolean` | Optional. Default is `false`. | Returns `string` | | prepareExternalUrl() | | --- | | `prepareExternalUrl(internal: string): string` Parameters | | | | | --- | --- | --- | | `internal` | `string` | | Returns `string` | | pushState() | | --- | | `pushState(state: any, title: string, path: string, queryParams: string)` Parameters | | | | | --- | --- | --- | | `state` | `any` | | | `title` | `string` | | | `path` | `string` | | | `queryParams` | `string` | | | | replaceState() | | --- | | `replaceState(state: any, title: string, path: string, queryParams: string)` Parameters | | | | | --- | --- | --- | | `state` | `any` | | | `title` | `string` | | | `path` | `string` | | | `queryParams` | `string` | | | | forward() | | --- | | `forward(): void` Parameters There are no parameters. Returns `void` | | back() | | --- | | `back(): void` Parameters There are no parameters. Returns `void` | | getState() | | --- | | `getState(): unknown` Parameters There are no parameters. Returns `unknown` | | historyGo() | | --- | | `historyGo(relativePosition: number = 0): void` Parameters | | | | | --- | --- | --- | | `relativePosition` | `number` | Optional. Default is `0`. | Returns `void` | Usage notes ----------- ### Example ``` import {HashLocationStrategy, Location, LocationStrategy} from '@angular/common'; import {Component} from '@angular/core'; @Component({ selector: 'hash-location', providers: [Location, {provide: LocationStrategy, useClass: HashLocationStrategy}], template: ` <h1>HashLocationStrategy</h1> Current URL is: <code>{{location.path()}}</code><br> Normalize: <code>/foo/bar/</code> is: <code>{{location.normalize('foo/bar')}}</code><br> ` }) export class HashLocationComponent { location: Location; constructor(location: Location) { this.location = location; } } ```
programming_docs
angular BrowserPlatformLocation BrowserPlatformLocation ======================= `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` `[PlatformLocation](platformlocation)` encapsulates all of the direct calls to platform APIs. This class should not be used directly by an application developer. Instead, use [`Location`](location). ``` class BrowserPlatformLocation extends PlatformLocation { href: string protocol: string hostname: string port: string pathname: string search: string hash: string getBaseHrefFromDOM(): string onPopState(fn: LocationChangeListener): VoidFunction onHashChange(fn: LocationChangeListener): VoidFunction pushState(state: any, title: string, url: string): void replaceState(state: any, title: string, url: string): void forward(): void back(): void historyGo(relativePosition: number = 0): void getState(): unknown // inherited from common/PlatformLocation abstract href: string abstract protocol: string abstract hostname: string abstract port: string abstract pathname: string abstract search: string abstract hash: string abstract getBaseHrefFromDOM(): string abstract getState(): unknown abstract onPopState(fn: LocationChangeListener): VoidFunction abstract onHashChange(fn: LocationChangeListener): VoidFunction abstract replaceState(state: any, title: string, url: string): void abstract pushState(state: any, title: string, url: string): void abstract forward(): void abstract back(): void historyGo(relativePosition: number)?: void } ``` Provided in ----------- * ``` 'platform' ``` Properties ---------- | Property | Description | | --- | --- | | `href: string` | Read-Only | | `protocol: string` | Read-Only | | `hostname: string` | Read-Only | | `port: string` | Read-Only | | `pathname: string` | | | `search: string` | Read-Only | | `hash: string` | Read-Only | Methods ------- | getBaseHrefFromDOM() | | --- | | `getBaseHrefFromDOM(): string` Parameters There are no parameters. Returns `string` | | onPopState() | | --- | | `onPopState(fn: LocationChangeListener): VoidFunction` Parameters | | | | | --- | --- | --- | | `fn` | `[LocationChangeListener](locationchangelistener)` | | Returns `VoidFunction` | | onHashChange() | | --- | | `onHashChange(fn: LocationChangeListener): VoidFunction` Parameters | | | | | --- | --- | --- | | `fn` | `[LocationChangeListener](locationchangelistener)` | | Returns `VoidFunction` | | pushState() | | --- | | `pushState(state: any, title: string, url: string): void` Parameters | | | | | --- | --- | --- | | `state` | `any` | | | `title` | `string` | | | `url` | `string` | | Returns `void` | | replaceState() | | --- | | `replaceState(state: any, title: string, url: string): void` Parameters | | | | | --- | --- | --- | | `state` | `any` | | | `title` | `string` | | | `url` | `string` | | Returns `void` | | forward() | | --- | | `forward(): void` Parameters There are no parameters. Returns `void` | | back() | | --- | | `back(): void` Parameters There are no parameters. Returns `void` | | historyGo() | | --- | | `historyGo(relativePosition: number = 0): void` Parameters | | | | | --- | --- | --- | | `relativePosition` | `number` | Optional. Default is `0`. | Returns `void` | | getState() | | --- | | `getState(): unknown` Parameters There are no parameters. Returns `unknown` | angular NgIf NgIf ==== `directive` A structural directive that conditionally includes a template based on the value of an expression coerced to Boolean. When the expression evaluates to true, Angular renders the template provided in a `then` clause, and when false or null, Angular renders the template provided in an optional `else` clause. The default template for the `else` clause is blank. [See more...](ngif#description) Exported from ------------- * [``` CommonModule ```](commonmodule) Selectors --------- * `[[ngIf](ngif)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)()[ngIf](ngif): T` | Write-Only The Boolean expression to evaluate as the condition for showing a template. | | `@[Input](../core/input)()ngIfThen: [TemplateRef](../core/templateref)<[NgIfContext](ngifcontext)<T>>` | Write-Only A template to show if the condition expression evaluates to true. | | `@[Input](../core/input)()ngIfElse: [TemplateRef](../core/templateref)<[NgIfContext](ngifcontext)<T>>` | Write-Only A template to show if the condition expression evaluates to false. | Description ----------- A [shorthand form](../../guide/structural-directives#asterisk) of the directive, `*[ngIf](ngif)="condition"`, is generally used, provided as an attribute of the anchor element for the inserted template. Angular expands this into a more explicit version, in which the anchor element is contained in an `[<ng-template>](../core/ng-template)` element. Simple form with shorthand syntax: ``` <div *ngIf="condition">Content to render when condition is true.</div> ``` Simple form with expanded syntax: ``` <ng-template [ngIf]="condition"><div>Content to render when condition is true.</div></ng-template> ``` Form with an "else" block: ``` <div *ngIf="condition; else elseBlock">Content to render when condition is true.</div> <ng-template #elseBlock>Content to render when condition is false.</ng-template> ``` Shorthand form with "then" and "else" blocks: ``` <div *ngIf="condition; then thenBlock else elseBlock"></div> <ng-template #thenBlock>Content to render when condition is true.</ng-template> <ng-template #elseBlock>Content to render when condition is false.</ng-template> ``` Form with storing the value locally: ``` <div *ngIf="condition as value; else elseBlock">{{value}}</div> <ng-template #elseBlock>Content to render when value is null.</ng-template> ``` The `*[ngIf](ngif)` directive is most commonly used to conditionally show an inline template, as seen in the following example. The default `else` template is blank. ``` @Component({ selector: 'ng-if-simple', template: ` <button (click)="show = !show">{{show ? 'hide' : 'show'}}</button> show = {{show}} <br> <div *ngIf="show">Text to show</div> ` }) export class NgIfSimple { show = true; } ``` ### Showing an alternative template using `else` To display a template when `expression` evaluates to false, use an `else` template binding as shown in the following example. The `else` binding points to an `[<ng-template>](../core/ng-template)` element labeled `#elseBlock`. The template can be defined anywhere in the component view, but is typically placed right after `[ngIf](ngif)` for readability. ``` @Component({ selector: 'ng-if-else', template: ` <button (click)="show = !show">{{show ? 'hide' : 'show'}}</button> show = {{show}} <br> <div *ngIf="show; else elseBlock">Text to show</div> <ng-template #elseBlock>Alternate text while primary text is hidden</ng-template> ` }) export class NgIfElse { show = true; } ``` ### Using an external `then` template In the previous example, the then-clause template is specified inline, as the content of the tag that contains the `[ngIf](ngif)` directive. You can also specify a template that is defined externally, by referencing a labeled `[<ng-template>](../core/ng-template)` element. When you do this, you can change which template to use at runtime, as shown in the following example. ``` @Component({ selector: 'ng-if-then-else', template: ` <button (click)="show = !show">{{show ? 'hide' : 'show'}}</button> <button (click)="switchPrimary()">Switch Primary</button> show = {{show}} <br> <div *ngIf="show; then thenBlock; else elseBlock">this is ignored</div> <ng-template #primaryBlock>Primary text to show</ng-template> <ng-template #secondaryBlock>Secondary text to show</ng-template> <ng-template #elseBlock>Alternate text while primary text is hidden</ng-template> ` }) export class NgIfThenElse implements OnInit { thenBlock: TemplateRef<any>|null = null; show = true; @ViewChild('primaryBlock', {static: true}) primaryBlock: TemplateRef<any>|null = null; @ViewChild('secondaryBlock', {static: true}) secondaryBlock: TemplateRef<any>|null = null; switchPrimary() { this.thenBlock = this.thenBlock === this.primaryBlock ? this.secondaryBlock : this.primaryBlock; } ngOnInit() { this.thenBlock = this.primaryBlock; } } ``` ### Storing a conditional result in a variable You might want to show a set of properties from the same object. If you are waiting for asynchronous data, the object can be undefined. In this case, you can use `[ngIf](ngif)` and store the result of the condition in a local variable as shown in the following example. ``` @Component({ selector: 'ng-if-as', template: ` <button (click)="nextUser()">Next User</button> <br> <div *ngIf="userObservable | async as user; else loading"> Hello {{user.last}}, {{user.first}}! </div> <ng-template #loading let-user>Waiting... (user is {{user|json}})</ng-template> ` }) export class NgIfAs { userObservable = new Subject<{first: string, last: string}>(); first = ['John', 'Mike', 'Mary', 'Bob']; firstIndex = 0; last = ['Smith', 'Novotny', 'Angular']; lastIndex = 0; nextUser() { let first = this.first[this.firstIndex++]; if (this.firstIndex >= this.first.length) this.firstIndex = 0; let last = this.last[this.lastIndex++]; if (this.lastIndex >= this.last.length) this.lastIndex = 0; this.userObservable.next({first, last}); } } ``` This code uses only one `[AsyncPipe](asyncpipe)`, so only one subscription is created. The conditional statement stores the result of `userStream|[async](asyncpipe)` in the local variable `user`. You can then bind the local `user` repeatedly. The conditional displays the data only if `userStream` returns a value, so you don't need to use the safe-navigation-operator (`?.`) to guard against null values when accessing properties. You can display an alternative template while waiting for the data. ### Shorthand syntax The shorthand syntax `*[ngIf](ngif)` expands into two separate template specifications for the "then" and "else" clauses. For example, consider the following shorthand statement, that is meant to show a loading page while waiting for data to be loaded. ``` <div class="hero-list" *ngIf="heroes else loading"> ... </div> <ng-template #loading> <div>Loading...</div> </ng-template> ``` You can see that the "else" clause references the `[<ng-template>](../core/ng-template)` with the `#loading` label, and the template for the "then" clause is provided as the content of the anchor element. However, when Angular expands the shorthand syntax, it creates another `[<ng-template>](../core/ng-template)` tag, with `[ngIf](ngif)` and `ngIfElse` directives. The anchor element containing the template for the "then" clause becomes the content of this unlabeled `[<ng-template>](../core/ng-template)` tag. ``` <ng-template [ngIf]="heroes" [ngIfElse]="loading"> <div class="hero-list"> ... </div> </ng-template> <ng-template #loading> <div>Loading...</div> </ng-template> ``` The presence of the implicit template object has implications for the nesting of structural directives. For more on this subject, see [Structural Directives](../../guide/structural-directives#one-per-element). Static properties ----------------- | Property | Description | | --- | --- | | `[static](../upgrade/static) ngTemplateGuard\_ngIf: 'binding'` | Assert the correct type of the expression bound to the `[ngIf](ngif)` input within the template. The presence of this static field is a signal to the Ivy template type check compiler that when the `[NgIf](ngif)` structural directive renders its template, the type of the expression bound to `[ngIf](ngif)` should be narrowed in some way. For `[NgIf](ngif)`, the binding expression itself is used to narrow its type, which allows the strictNullChecks feature of TypeScript to work with `[NgIf](ngif)`. | Static methods -------------- | ngTemplateContextGuard() | | --- | | Asserts the correct type of the context for the template that `[NgIf](ngif)` will render. | | `static ngTemplateContextGuard<T>(dir: NgIf<T>, ctx: any): ctx is NgIfContext<Exclude<T, false | 0 | '' | null | undefined>>` Parameters | | | | | --- | --- | --- | | `dir` | `[NgIf](ngif)<T>` | | | `ctx` | `any` | | Returns `ctx is [NgIfContext](ngifcontext)<Exclude<T, false | 0 | '' | null | undefined>>` | | The presence of this method is a signal to the Ivy template type-check compiler that the `[NgIf](ngif)` structural directive renders its template with a specific context type. | angular provideImgixLoader provideImgixLoader ================== `const` Function that generates an ImageLoader for Imgix and turns it into an Angular provider. ### `const provideImgixLoader: (path: string) => Provider[];` angular DatePipe DatePipe ======== `pipe` Formats a date value according to locale rules. [See more...](datepipe#description) ### `{{ value_expression | date [ : format [ : timezone [ : locale ] ] ] }}` #### Exported from * [``` CommonModule ```](commonmodule) Input value ----------- | | | | | --- | --- | --- | | `value` | `string | number | Date` | | Parameters ---------- | | | | | --- | --- | --- | | `format` | `string` | Optional. Default is `undefined`. | | `timezone` | `string` | Optional. Default is `undefined`. | | `locale` | `string` | Optional. Default is `undefined`. | See also -------- * `[formatDate](formatdate)()` Description ----------- `[DatePipe](datepipe)` is executed only when it detects a pure change to the input value. A pure change is either a change to a primitive input value (such as `String`, `Number`, `Boolean`, or `Symbol`), or a changed object reference (such as `Date`, `Array`, `Function`, or `Object`). Note that mutating a `Date` object does not cause the pipe to be rendered again. To ensure that the pipe is executed, you must create a new `Date` object. Only the `en-US` locale data comes with Angular. To localize dates in another language, you must import the corresponding locale data. See the [I18n guide](../../guide/i18n-common-format-data-locale) for more information. The time zone of the formatted value can be specified either by passing it in as the second parameter of the pipe, or by setting the default through the `[DATE\_PIPE\_DEFAULT\_OPTIONS](date_pipe_default_options)` injection token. The value that is passed in as the second parameter takes precedence over the one defined using the injection token. Further information is available in the [Usage Notes...](datepipe#usage-notes) Usage notes ----------- The result of this pipe is not reevaluated when the input is mutated. To avoid the need to reformat the date on every change-detection cycle, treat the date as an immutable object and change the reference when the pipe needs to run again. #### Pre-defined format options | Option | Equivalent to | Examples (given in `en-US` locale) | | --- | --- | --- | | `'short'` | `'M/d/yy, h:mm a'` | `6/15/15, 9:03 AM` | | `'medium'` | `'MMM d, y, h:mm:ss a'` | `Jun 15, 2015, 9:03:01 AM` | | `'long'` | `'MMMM d, y, h:mm:ss a z'` | `June 15, 2015 at 9:03:01 AM GMT+1` | | `'full'` | `'EEEE, MMMM d, y, h:mm:ss a zzzz'` | `Monday, June 15, 2015 at 9:03:01 AM GMT+01:00` | | `'shortDate'` | `'M/d/yy'` | `6/15/15` | | `'mediumDate'` | `'MMM d, y'` | `Jun 15, 2015` | | `'longDate'` | `'MMMM d, y'` | `June 15, 2015` | | `'fullDate'` | `'EEEE, MMMM d, y'` | `Monday, June 15, 2015` | | `'shortTime'` | `'h:mm a'` | `9:03 AM` | | `'mediumTime'` | `'h:mm:ss a'` | `9:03:01 AM` | | `'longTime'` | `'h:mm:ss a z'` | `9:03:01 AM GMT+1` | | `'fullTime'` | `'h:mm:ss a zzzz'` | `9:03:01 AM GMT+01:00` | #### Custom format options You can construct a format string using symbols to specify the components of a date-time value, as described in the following table. Format details depend on the locale. Fields marked with (\*) are only available in the extra data set for the given locale. | Field type | Format | Description | Example Value | | --- | --- | --- | --- | | Era | G, GG & GGG | Abbreviated | AD | | | GGGG | Wide | Anno Domini | | | GGGGG | Narrow | A | | Year | y | Numeric: minimum digits | 2, 20, 201, 2017, 20173 | | | yy | Numeric: 2 digits + zero padded | 02, 20, 01, 17, 73 | | | yyy | Numeric: 3 digits + zero padded | 002, 020, 201, 2017, 20173 | | | yyyy | Numeric: 4 digits or more + zero padded | 0002, 0020, 0201, 2017, 20173 | | Week-numbering year | Y | Numeric: minimum digits | 2, 20, 201, 2017, 20173 | | | YY | Numeric: 2 digits + zero padded | 02, 20, 01, 17, 73 | | | YYY | Numeric: 3 digits + zero padded | 002, 020, 201, 2017, 20173 | | | YYYY | Numeric: 4 digits or more + zero padded | 0002, 0020, 0201, 2017, 20173 | | Month | M | Numeric: 1 digit | 9, 12 | | | MM | Numeric: 2 digits + zero padded | 09, 12 | | | MMM | Abbreviated | Sep | | | MMMM | Wide | September | | | MMMMM | Narrow | S | | Month standalone | L | Numeric: 1 digit | 9, 12 | | | LL | Numeric: 2 digits + zero padded | 09, 12 | | | LLL | Abbreviated | Sep | | | LLLL | Wide | September | | | LLLLL | Narrow | S | | Week of year | w | Numeric: minimum digits | 1... 53 | | | ww | Numeric: 2 digits + zero padded | 01... 53 | | Week of month | W | Numeric: 1 digit | 1... 5 | | Day of month | d | Numeric: minimum digits | 1 | | | dd | Numeric: 2 digits + zero padded | 01 | | Week day | E, EE & EEE | Abbreviated | Tue | | | EEEE | Wide | Tuesday | | | EEEEE | Narrow | T | | | EEEEEE | Short | Tu | | Week day standalone | c, cc | Numeric: 1 digit | 2 | | | ccc | Abbreviated | Tue | | | cccc | Wide | Tuesday | | | ccccc | Narrow | T | | | cccccc | Short | Tu | | Period | a, aa & aaa | Abbreviated | am/pm or AM/PM | | | aaaa | Wide (fallback to `a` when missing) | ante meridiem/post meridiem | | | aaaaa | Narrow | a/p | | Period\* | B, BB & BBB | Abbreviated | mid. | | | BBBB | Wide | am, pm, midnight, noon, morning, afternoon, evening, night | | | BBBBB | Narrow | md | | Period standalone\* | b, bb & bbb | Abbreviated | mid. | | | bbbb | Wide | am, pm, midnight, noon, morning, afternoon, evening, night | | | bbbbb | Narrow | md | | Hour 1-12 | h | Numeric: minimum digits | 1, 12 | | | hh | Numeric: 2 digits + zero padded | 01, 12 | | Hour 0-23 | H | Numeric: minimum digits | 0, 23 | | | HH | Numeric: 2 digits + zero padded | 00, 23 | | Minute | m | Numeric: minimum digits | 8, 59 | | | mm | Numeric: 2 digits + zero padded | 08, 59 | | Second | s | Numeric: minimum digits | 0... 59 | | | ss | Numeric: 2 digits + zero padded | 00... 59 | | Fractional seconds | S | Numeric: 1 digit | 0... 9 | | | SS | Numeric: 2 digits + zero padded | 00... 99 | | | SSS | Numeric: 3 digits + zero padded (= milliseconds) | 000... 999 | | Zone | z, zz & zzz | Short specific non location format (fallback to O) | GMT-8 | | | zzzz | Long specific non location format (fallback to OOOO) | GMT-08:00 | | | Z, ZZ & ZZZ | ISO8601 basic format | -0800 | | | ZZZZ | Long localized GMT format | GMT-8:00 | | | ZZZZZ | ISO8601 extended format + Z indicator for offset 0 (= XXXXX) | -08:00 | | | O, OO & OOO | Short localized GMT format | GMT-8 | | | OOOO | Long localized GMT format | GMT-08:00 | #### Format examples These examples transform a date into various formats, assuming that `dateObj` is a JavaScript `Date` object for year: 2015, month: 6, day: 15, hour: 21, minute: 43, second: 11, given in the local time for the `en-US` locale. ``` {{ dateObj | date }} // output is 'Jun 15, 2015' {{ dateObj | date:'medium' }} // output is 'Jun 15, 2015, 9:43:11 PM' {{ dateObj | date:'shortTime' }} // output is '9:43 PM' {{ dateObj | date:'mm:ss' }} // output is '43:11' ``` #### Usage example The following component uses a date pipe to display the current date in different formats. ``` @Component({ selector: 'date-pipe', template: `<div> <p>Today is {{today | date}}</p> <p>Or if you prefer, {{today | date:'fullDate'}}</p> <p>The time is {{today | date:'h:mm a z'}}</p> </div>` }) // Get the current date and time as a date-time value. export class DatePipeComponent { today: number = Date.now(); } ```
programming_docs
angular APP_BASE_HREF APP\_BASE\_HREF =============== `const` A predefined [DI token](../../guide/glossary#di-token) for the base href to be used with the `[PathLocationStrategy](pathlocationstrategy)`. The base href is the URL prefix that should be preserved when generating and recognizing URLs. ### `const APP_BASE_HREF: InjectionToken<string>;` #### Usage notes The following example shows how to use this token to configure the root app injector with a base href value, so that the DI framework can supply the dependency anywhere in the app. ``` import {Component, NgModule} from '@angular/core'; import {APP_BASE_HREF} from '@angular/common'; @NgModule({ providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}] }) class AppModule {} ``` angular PathLocationStrategy PathLocationStrategy ==================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A [`LocationStrategy`](locationstrategy) used to configure the [`Location`](location) service to represent its state in the [path](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax) of the browser's URL. [See more...](pathlocationstrategy#description) ``` class PathLocationStrategy extends LocationStrategy implements OnDestroy { onPopState(fn: LocationChangeListener): void getBaseHref(): string prepareExternalUrl(internal: string): string path(includeHash: boolean = false): string pushState(state: any, title: string, url: string, queryParams: string) replaceState(state: any, title: string, url: string, queryParams: string) forward(): void back(): void getState(): unknown historyGo(relativePosition: number = 0): void // inherited from common/LocationStrategy abstract path(includeHash?: boolean): string abstract prepareExternalUrl(internal: string): string abstract getState(): unknown abstract pushState(state: any, title: string, url: string, queryParams: string): void abstract replaceState(state: any, title: string, url: string, queryParams: string): void abstract forward(): void abstract back(): void historyGo(relativePosition: number)?: void abstract onPopState(fn: LocationChangeListener): void abstract getBaseHref(): string } ``` Provided in ----------- * ``` 'root' ``` Description ----------- If you're using `[PathLocationStrategy](pathlocationstrategy)`, you may provide a [`APP_BASE_HREF`](app_base_href) or add a `<base href>` element to the document to override the default. For instance, if you provide an `[APP\_BASE\_HREF](app_base_href)` of `'/my/app/'` and call `location.go('/foo')`, the browser's URL will become `example.com/my/app/foo`. To ensure all relative URIs resolve correctly, the `<base href>` and/or `[APP\_BASE\_HREF](app_base_href)` should end with a `/`. Similarly, if you add `<base href='/my/app/'/>` to the document and call `location.go('/foo')`, the browser's URL will become `example.com/my/app/foo`. Note that when using `[PathLocationStrategy](pathlocationstrategy)`, neither the query nor the fragment in the `<base href>` will be preserved, as outlined by the [RFC](https://tools.ietf.org/html/rfc3986#section-5.2.2). Further information is available in the [Usage Notes...](pathlocationstrategy#usage-notes) Methods ------- | onPopState() | | --- | | `onPopState(fn: LocationChangeListener): void` Parameters | | | | | --- | --- | --- | | `fn` | `[LocationChangeListener](locationchangelistener)` | | Returns `void` | | getBaseHref() | | --- | | `getBaseHref(): string` Parameters There are no parameters. Returns `string` | | prepareExternalUrl() | | --- | | `prepareExternalUrl(internal: string): string` Parameters | | | | | --- | --- | --- | | `internal` | `string` | | Returns `string` | | path() | | --- | | `path(includeHash: boolean = false): string` Parameters | | | | | --- | --- | --- | | `includeHash` | `boolean` | Optional. Default is `false`. | Returns `string` | | pushState() | | --- | | `pushState(state: any, title: string, url: string, queryParams: string)` Parameters | | | | | --- | --- | --- | | `state` | `any` | | | `title` | `string` | | | `url` | `string` | | | `queryParams` | `string` | | | | replaceState() | | --- | | `replaceState(state: any, title: string, url: string, queryParams: string)` Parameters | | | | | --- | --- | --- | | `state` | `any` | | | `title` | `string` | | | `url` | `string` | | | `queryParams` | `string` | | | | forward() | | --- | | `forward(): void` Parameters There are no parameters. Returns `void` | | back() | | --- | | `back(): void` Parameters There are no parameters. Returns `void` | | getState() | | --- | | `getState(): unknown` Parameters There are no parameters. Returns `unknown` | | historyGo() | | --- | | `historyGo(relativePosition: number = 0): void` Parameters | | | | | --- | --- | --- | | `relativePosition` | `number` | Optional. Default is `0`. | Returns `void` | Usage notes ----------- ### Example ``` import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common'; import {Component} from '@angular/core'; @Component({ selector: 'path-location', providers: [Location, {provide: LocationStrategy, useClass: PathLocationStrategy}], template: ` <h1>PathLocationStrategy</h1> Current URL is: <code>{{location.path()}}</code><br> Normalize: <code>/foo/bar/</code> is: <code>{{location.normalize('foo/bar')}}</code><br> ` }) export class PathLocationComponent { location: Location; constructor(location: Location) { this.location = location; } } ``` angular isPlatformServer isPlatformServer ================ `function` Returns whether a platform id represents a server platform. ### `isPlatformServer(platformId: Object): boolean` ###### Parameters | | | | | --- | --- | --- | | `platformId` | `Object` | | ###### Returns `boolean` angular CommonModule CommonModule ============ `ngmodule` Exports all the basic Angular directives and pipes, such as `[NgIf](ngif)`, `[NgForOf](ngforof)`, `[DecimalPipe](decimalpipe)`, and so on. Re-exported by `[BrowserModule](../platform-browser/browsermodule)`, which is included automatically in the root `AppModule` when you create a new app with the CLI `new` command. ``` class CommonModule { } ``` Directives ---------- | Name | Description | | --- | --- | | [``` NgClass ```](ngclass) | Adds and removes CSS classes on an HTML element. | | [``` NgComponentOutlet ```](ngcomponentoutlet) | Instantiates a [`Component`](../core/component) type and inserts its Host View into the current View. `[NgComponentOutlet](ngcomponentoutlet)` provides a declarative approach for dynamic component creation. | | [``` NgFor ```](ngfor) | A [structural directive](../../guide/structural-directives) that renders a template for each item in a collection. The directive is placed on an element, which becomes the parent of the cloned templates. | | [``` NgForOf ```](ngforof) | A [structural directive](../../guide/structural-directives) that renders a template for each item in a collection. The directive is placed on an element, which becomes the parent of the cloned templates. | | [``` NgIf ```](ngif) | A structural directive that conditionally includes a template based on the value of an expression coerced to Boolean. When the expression evaluates to true, Angular renders the template provided in a `then` clause, and when false or null, Angular renders the template provided in an optional `else` clause. The default template for the `else` clause is blank. | | [``` NgPlural ```](ngplural) | Adds / removes DOM sub-trees based on a numeric value. Tailored for pluralization. | | [``` NgPluralCase ```](ngpluralcase) | Creates a view that will be added/removed from the parent [`NgPlural`](ngplural) when the given expression matches the plural expression according to CLDR rules. | | [``` NgStyle ```](ngstyle) | An attribute directive that updates styles for the containing HTML element. Sets one or more style properties, specified as colon-separated key-value pairs. The key is a style name, with an optional `.<unit>` suffix (such as 'top.px', 'font-style.em'). The value is an expression to be evaluated. The resulting non-null value, expressed in the given unit, is assigned to the given style property. If the result of evaluation is null, the corresponding style is removed. | | [``` NgSwitch ```](ngswitch) | The `[[ngSwitch](ngswitch)]` directive on a container specifies an expression to match against. The expressions to match are provided by `[ngSwitchCase](ngswitchcase)` directives on views within the container.* Every view that matches is rendered. * If there are no matches, a view with the `[ngSwitchDefault](ngswitchdefault)` directive is rendered. * Elements within the `[[NgSwitch](ngswitch)]` statement but outside of any `[NgSwitchCase](ngswitchcase)` or `[ngSwitchDefault](ngswitchdefault)` directive are preserved at the location. | | [``` NgSwitchCase ```](ngswitchcase) | Provides a switch case expression to match against an enclosing `[ngSwitch](ngswitch)` expression. When the expressions match, the given `[NgSwitchCase](ngswitchcase)` template is rendered. If multiple match expressions match the switch expression value, all of them are displayed. | | [``` NgSwitchDefault ```](ngswitchdefault) | Creates a view that is rendered when no `[NgSwitchCase](ngswitchcase)` expressions match the `[NgSwitch](ngswitch)` expression. This statement should be the final case in an `[NgSwitch](ngswitch)`. | | [``` NgTemplateOutlet ```](ngtemplateoutlet) | Inserts an embedded view from a prepared `[TemplateRef](../core/templateref)`. | Pipes ----- | Name | Description | | --- | --- | | [``` AsyncPipe ```](asyncpipe) | Unwraps a value from an asynchronous primitive. | | [``` CurrencyPipe ```](currencypipe) | Transforms a number to a currency string, formatted according to locale rules that determine group sizing and separator, decimal-point character, and other locale-specific configurations. | | [``` DatePipe ```](datepipe) | Formats a date value according to locale rules. | | [``` DecimalPipe ```](decimalpipe) | Formats a value according to digit options and locale rules. Locale determines group sizing and separator, decimal point character, and other locale-specific configurations. | | [``` I18nPluralPipe ```](i18npluralpipe) | Maps a value to a string that pluralizes the value according to locale rules. | | [``` I18nSelectPipe ```](i18nselectpipe) | Generic selector that displays the string that matches the current value. | | [``` JsonPipe ```](jsonpipe) | Converts a value into its JSON-format representation. Useful for debugging. | | [``` KeyValuePipe ```](keyvaluepipe) | Transforms Object or Map into an array of key value pairs. | | [``` LowerCasePipe ```](lowercasepipe) | Transforms text to all lower case. | | [``` PercentPipe ```](percentpipe) | Transforms a number to a percentage string, formatted according to locale rules that determine group sizing and separator, decimal-point character, and other locale-specific configurations. | | [``` SlicePipe ```](slicepipe) | Creates a new `Array` or `String` containing a subset (slice) of the elements. | | [``` TitleCasePipe ```](titlecasepipe) | Transforms text to title case. Capitalizes the first letter of each word and transforms the rest of the word to lower case. Words are delimited by any whitespace character, such as a space, tab, or line-feed character. | | [``` UpperCasePipe ```](uppercasepipe) | Transforms text to all upper case. | angular NgTemplateOutlet NgTemplateOutlet ================ `directive` Inserts an embedded view from a prepared `[TemplateRef](../core/templateref)`. [See more...](ngtemplateoutlet#description) Exported from ------------- * [``` CommonModule ```](commonmodule) Selectors --------- * `[[ngTemplateOutlet](ngtemplateoutlet)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)()ngTemplateOutletContext: Object | null` | A context object to attach to the [`EmbeddedViewRef`](../core/embeddedviewref). This should be an object, the object's keys will be available for binding by the local template `let` declarations. Using the key `$implicit` in the context object will set its value as default. | | `@[Input](../core/input)()[ngTemplateOutlet](ngtemplateoutlet): [TemplateRef](../core/templateref)<any> | null` | A string defining the template reference and optionally the context object for the template. | | `@[Input](../core/input)()ngTemplateOutletInjector: [Injector](../core/injector) | null` | Injector to be used within the embedded view. | Description ----------- You can attach a context object to the `[EmbeddedViewRef](../core/embeddedviewref)` by setting `[ngTemplateOutletContext]`. `[ngTemplateOutletContext]` should be an object, the object's keys will be available for binding by the local template `let` declarations. ``` <ng-container *ngTemplateOutlet="templateRefExp; context: contextExp"></ng-container> ``` Using the key `$implicit` in the context object will set its value as default. ### Example ``` @Component({ selector: 'ng-template-outlet-example', template: ` <ng-container *ngTemplateOutlet="greet"></ng-container> <hr> <ng-container *ngTemplateOutlet="eng; context: myContext"></ng-container> <hr> <ng-container *ngTemplateOutlet="svk; context: myContext"></ng-container> <hr> <ng-template #greet><span>Hello</span></ng-template> <ng-template #eng let-name><span>Hello {{name}}!</span></ng-template> <ng-template #svk let-person="localSk"><span>Ahoj {{person}}!</span></ng-template> ` }) export class NgTemplateOutletExample { myContext = {$implicit: 'World', localSk: 'Svet'}; } ``` angular formatCurrency formatCurrency ============== `function` Formats a number as currency using locale rules. ### `formatCurrency(value: number, locale: string, currency: string, currencyCode?: string, digitsInfo?: string): string` ###### Parameters | | | | | --- | --- | --- | | `value` | `number` | The number to format. | | `locale` | `string` | A locale code for the locale format rules to use. | | `[currency](currencypipe)` | `string` | A string containing the currency symbol or its name, such as "$" or "Canadian Dollar". Used in output string, but does not affect the operation of the function. | | `currencyCode` | `string` | The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, such as `USD` for the US dollar and `EUR` for the euro. Used to determine the number of digits in the decimal part. Optional. Default is `undefined`. | | `digitsInfo` | `string` | Decimal representation options, specified by a string in the following format: `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `[DecimalPipe](decimalpipe)` for more details. Optional. Default is `undefined`. | ###### Returns `string`: The formatted currency value. See also -------- * `[formatNumber](formatnumber)()` * `[DecimalPipe](decimalpipe)` * [Internationalization (i18n) Guide](../../guide/i18n-overview) angular NgPluralCase NgPluralCase ============ `directive` Creates a view that will be added/removed from the parent [`NgPlural`](ngplural) when the given expression matches the plural expression according to CLDR rules. Exported from ------------- * [``` CommonModule ```](commonmodule) Selectors --------- * `[[ngPluralCase](ngpluralcase)]` Properties ---------- | Property | Description | | --- | --- | | `value: string` | | Description ----------- ``` <some-element [ngPlural]="value"> <ng-template ngPluralCase="=0">...</ng-template> <ng-template ngPluralCase="other">...</ng-template> </some-element> ``` See [`NgPlural`](ngplural) for more details and example. angular getLocaleExtraDayPeriods getLocaleExtraDayPeriods ======================== `function` Retrieves locale-specific day periods, which indicate roughly how a day is broken up in different languages. For example, for `en-US`, periods are morning, noon, afternoon, evening, and midnight. [See more...](getlocaleextradayperiods#description) ### `getLocaleExtraDayPeriods(locale: string, formStyle: FormStyle, width: TranslationWidth): string[]` ###### Parameters | | | | | --- | --- | --- | | `locale` | `string` | A locale code for the locale format rules to use. | | `formStyle` | `[FormStyle](formstyle)` | The required grammatical form. | | `width` | `[TranslationWidth](translationwidth)` | The required character width. | ###### Returns `string[]`: The translated day-period strings. See also -------- * `[getLocaleExtraDayPeriodRules](getlocaleextradayperiodrules)()` * [Internationalization (i18n) Guide](../../guide/i18n-overview) Description ----------- This functionality is only available when you have loaded the full locale data. See the ["I18n guide"](../../guide/i18n-common-format-data-locale). angular NgIfContext NgIfContext =========== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` ``` class NgIfContext<T = unknown> { $implicit: T ngIf: T } ``` Properties ---------- | Property | Description | | --- | --- | | `$implicit: T` | | | `[ngIf](ngif): T` | | angular AsyncPipe AsyncPipe ========= `pipe` `impure` Unwraps a value from an asynchronous primitive. [See more...](asyncpipe#description) ### `{{ obj_expression | async }}` #### Exported from * [``` CommonModule ```](commonmodule) Input value ----------- | | | | | --- | --- | --- | | `obj` | `Observable<T> | Subscribable<T> | Promise<T>` | | Description ----------- The `[async](asyncpipe)` pipe subscribes to an `Observable` or `Promise` and returns the latest value it has emitted. When a new value is emitted, the `[async](asyncpipe)` pipe marks the component to be checked for changes. When the component gets destroyed, the `[async](asyncpipe)` pipe unsubscribes automatically to avoid potential memory leaks. When the reference of the expression changes, the `[async](asyncpipe)` pipe automatically unsubscribes from the old `Observable` or `Promise` and subscribes to the new one. Further information is available in the [Usage Notes...](asyncpipe#usage-notes) Usage notes ----------- #### Examples This example binds a `Promise` to the view. Clicking the `[Resolve](../router/resolve)` button resolves the promise. ``` @Component({ selector: 'async-promise-pipe', template: `<div> <code>promise|async</code>: <button (click)="clicked()">{{ arrived ? 'Reset' : 'Resolve' }}</button> <span>Wait for it... {{ greeting | async }}</span> </div>` }) export class AsyncPromisePipeComponent { greeting: Promise<string>|null = null; arrived: boolean = false; private resolve: Function|null = null; constructor() { this.reset(); } reset() { this.arrived = false; this.greeting = new Promise<string>((resolve, reject) => { this.resolve = resolve; }); } clicked() { if (this.arrived) { this.reset(); } else { this.resolve!('hi there!'); this.arrived = true; } } } ``` It's also possible to use `[async](asyncpipe)` with Observables. The example below binds the `time` Observable to the view. The Observable continuously updates the view with the current time. ``` @Component({ selector: 'async-observable-pipe', template: '<div><code>observable|async</code>: Time: {{ time | async }}</div>' }) export class AsyncObservablePipeComponent { time = new Observable<string>((observer: Observer<string>) => { setInterval(() => observer.next(new Date().toString()), 1000); }); } ``` angular provideImageKitLoader provideImageKitLoader ===================== `const` Function that generates an ImageLoader for ImageKit and turns it into an Angular provider. ### `const provideImageKitLoader: (path: string) => Provider[];`
programming_docs
angular PlatformLocation PlatformLocation ================ `class` This class should not be used directly by an application developer. Instead, use [`Location`](location). [See more...](platformlocation#description) ``` abstract class PlatformLocation { abstract href: string abstract protocol: string abstract hostname: string abstract port: string abstract pathname: string abstract search: string abstract hash: string abstract getBaseHrefFromDOM(): string abstract getState(): unknown abstract onPopState(fn: LocationChangeListener): VoidFunction abstract onHashChange(fn: LocationChangeListener): VoidFunction abstract replaceState(state: any, title: string, url: string): void abstract pushState(state: any, title: string, url: string): void abstract forward(): void abstract back(): void historyGo(relativePosition: number)?: void } ``` Subclasses ---------- * `[BrowserPlatformLocation](browserplatformlocation)` * `[MockPlatformLocation](testing/mockplatformlocation)` Provided in ----------- * ``` 'platform' ``` * [``` BrowserTestingModule ```](../platform-browser/testing/browsertestingmodule) Description ----------- `[PlatformLocation](platformlocation)` encapsulates all calls to DOM APIs, which allows the Router to be platform-agnostic. This means that we can have different implementation of `[PlatformLocation](platformlocation)` for the different platforms that Angular supports. For example, `@angular/platform-browser` provides an implementation specific to the browser environment, while `@angular/platform-server` provides one suitable for use with server-side rendering. The `[PlatformLocation](platformlocation)` class is used directly by all implementations of [`LocationStrategy`](locationstrategy) when they need to interact with the DOM APIs like pushState, popState, etc. [`LocationStrategy`](locationstrategy) in turn is used by the [`Location`](location) service which is used directly by the [`Router`](../router/router) in order to navigate between routes. Since all interactions between [`Router`](../router/router) / [`Location`](location) / [`LocationStrategy`](locationstrategy) and DOM APIs flow through the `[PlatformLocation](platformlocation)` class, they are all platform-agnostic. Properties ---------- | Property | Description | | --- | --- | | `abstract href: string` | Read-Only | | `abstract protocol: string` | Read-Only | | `abstract hostname: string` | Read-Only | | `abstract port: string` | Read-Only | | `abstract pathname: string` | Read-Only | | `abstract search: string` | Read-Only | | `abstract hash: string` | Read-Only | Methods ------- | getBaseHrefFromDOM() | | --- | | `abstract getBaseHrefFromDOM(): string` Parameters There are no parameters. Returns `string` | | getState() | | --- | | `abstract getState(): unknown` Parameters There are no parameters. Returns `unknown` | | onPopState() | | --- | | Returns a function that, when executed, removes the `popstate` event handler. | | `abstract onPopState(fn: LocationChangeListener): VoidFunction` Parameters | | | | | --- | --- | --- | | `fn` | `[LocationChangeListener](locationchangelistener)` | | Returns `VoidFunction` | | onHashChange() | | --- | | Returns a function that, when executed, removes the `hashchange` event handler. | | `abstract onHashChange(fn: LocationChangeListener): VoidFunction` Parameters | | | | | --- | --- | --- | | `fn` | `[LocationChangeListener](locationchangelistener)` | | Returns `VoidFunction` | | replaceState() | | --- | | `abstract replaceState(state: any, title: string, url: string): void` Parameters | | | | | --- | --- | --- | | `state` | `any` | | | `title` | `string` | | | `url` | `string` | | Returns `void` | | pushState() | | --- | | `abstract pushState(state: any, title: string, url: string): void` Parameters | | | | | --- | --- | --- | | `state` | `any` | | | `title` | `string` | | | `url` | `string` | | Returns `void` | | forward() | | --- | | `abstract forward(): void` Parameters There are no parameters. Returns `void` | | back() | | --- | | `abstract back(): void` Parameters There are no parameters. Returns `void` | | historyGo() | | --- | | `historyGo(relativePosition: number)?: void` Parameters | | | | | --- | --- | --- | | `relativePosition` | `number` | | Returns `void` | angular I18nPluralPipe I18nPluralPipe ============== `pipe` Maps a value to a string that pluralizes the value according to locale rules. ### `{{ value_expression | i18nPlural : pluralMap [ : locale ] }}` #### Exported from * [``` CommonModule ```](commonmodule) Input value ----------- | | | | | --- | --- | --- | | `value` | `number` | the number to be formatted | Parameters ---------- | | | | | --- | --- | --- | | `pluralMap` | `object` | an object that mimics the ICU format, see <https://unicode-org.github.io/icu/userguide/format_parse/messages/>. | | `locale` | `string` | a `string` defining the locale to use (uses the current [`LOCALE_ID`](../core/locale_id) by default). Optional. Default is `undefined`. | Usage notes ----------- #### Example ``` @Component({ selector: 'i18n-plural-pipe', template: `<div>{{ messages.length | i18nPlural: messageMapping }}</div>` }) export class I18nPluralPipeComponent { messages: any[] = ['Message 1']; messageMapping: {[k: string]: string} = {'=0': 'No messages.', '=1': 'One message.', 'other': '# messages.'}; } ``` angular TranslationWidth TranslationWidth ================ `enum` String widths available for translations. The specific character widths are locale-specific. Examples are given for the word "Sunday" in English. ``` enum TranslationWidth { Narrow Abbreviated Wide Short } ``` Members ------- | Member | Description | | --- | --- | | `Narrow` | 1 character for `en-US`. For example: 'S' | | `Abbreviated` | 3 characters for `en-US`. For example: 'Sun' | | `Wide` | Full length for `en-US`. For example: "Sunday" | | `Short` | 2 characters for `en-US`, For example: "Su" | angular NgSwitchCase NgSwitchCase ============ `directive` Provides a switch case expression to match against an enclosing `[ngSwitch](ngswitch)` expression. When the expressions match, the given `[NgSwitchCase](ngswitchcase)` template is rendered. If multiple match expressions match the switch expression value, all of them are displayed. See also -------- * `[NgSwitch](ngswitch)` * `[NgSwitchDefault](ngswitchdefault)` Exported from ------------- * [``` CommonModule ```](commonmodule) Selectors --------- * `[[ngSwitchCase](ngswitchcase)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)()[ngSwitchCase](ngswitchcase): any` | Stores the HTML template to be selected on match. | Description ----------- Within a switch container, `*[ngSwitchCase](ngswitchcase)` statements specify the match expressions as attributes. Include `*[ngSwitchDefault](ngswitchdefault)` as the final case. ``` <container-element [ngSwitch]="switch_expression"> <some-element *ngSwitchCase="match_expression_1">...</some-element> ... <some-element *ngSwitchDefault>...</some-element> </container-element> ``` Each switch-case statement contains an in-line HTML template or template reference that defines the subtree to be selected if the value of the match expression matches the value of the switch expression. Unlike JavaScript, which uses strict equality, Angular uses loose equality. This means that the empty string, `""` matches 0. angular getLocaleWeekEndRange getLocaleWeekEndRange ===================== `function` Range of week days that are considered the week-end for the given locale. ### `getLocaleWeekEndRange(locale: string): [ WeekDay, WeekDay ]` ###### Parameters | | | | | --- | --- | --- | | `locale` | `string` | A locale code for the locale format rules to use. | ###### Returns `[ [WeekDay](weekday), [WeekDay](weekday) ]`: The range of day values, `[startDay, endDay]`. See also -------- * [Internationalization (i18n) Guide](../../guide/i18n-overview) angular NgLocaleLocalization NgLocaleLocalization ==================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Returns the plural case based on the locale ``` class NgLocaleLocalization extends NgLocalization { protected locale: string getPluralCategory(value: any, locale?: string): string // inherited from common/NgLocalization abstract getPluralCategory(value: any, locale?: string): string } ``` Properties ---------- | Property | Description | | --- | --- | | `protected locale: string` | | Methods ------- | getPluralCategory() | | --- | | `getPluralCategory(value: any, locale?: string): string` Parameters | | | | | --- | --- | --- | | `value` | `any` | | | `locale` | `string` | Optional. Default is `undefined`. | Returns `string` | angular isPlatformBrowser isPlatformBrowser ================= `function` Returns whether a platform id represents a browser platform. ### `isPlatformBrowser(platformId: Object): boolean` ###### Parameters | | | | | --- | --- | --- | | `platformId` | `Object` | | ###### Returns `boolean` angular NgSwitch NgSwitch ======== `directive` The `[[ngSwitch](ngswitch)]` directive on a container specifies an expression to match against. The expressions to match are provided by `[ngSwitchCase](ngswitchcase)` directives on views within the container. * Every view that matches is rendered. * If there are no matches, a view with the `[ngSwitchDefault](ngswitchdefault)` directive is rendered. * Elements within the `[[NgSwitch](ngswitch)]` statement but outside of any `[NgSwitchCase](ngswitchcase)` or `[ngSwitchDefault](ngswitchdefault)` directive are preserved at the location. See also -------- * `[NgSwitchCase](ngswitchcase)` * `[NgSwitchDefault](ngswitchdefault)` * [Structural Directives](../../guide/structural-directives) Exported from ------------- * [``` CommonModule ```](commonmodule) Selectors --------- * `[[ngSwitch](ngswitch)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)()[ngSwitch](ngswitch): any` | Write-Only | Description ----------- Define a container element for the directive, and specify the switch expression to match against as an attribute: ``` <container-element [ngSwitch]="switch_expression"> ``` Within the container, `*[ngSwitchCase](ngswitchcase)` statements specify the match expressions as attributes. Include `*[ngSwitchDefault](ngswitchdefault)` as the final case. ``` <container-element [ngSwitch]="switch_expression"> <some-element *ngSwitchCase="match_expression_1">...</some-element> ... <some-element *ngSwitchDefault>...</some-element> </container-element> ``` ### Usage Examples The following example shows how to use more than one case to display the same view: ``` <container-element [ngSwitch]="switch_expression"> <!-- the same view can be shown in more than one case --> <some-element *ngSwitchCase="match_expression_1">...</some-element> <some-element *ngSwitchCase="match_expression_2">...</some-element> <some-other-element *ngSwitchCase="match_expression_3">...</some-other-element> <!--default case when there are no matches --> <some-element *ngSwitchDefault>...</some-element> </container-element> ``` The following example shows how cases can be nested: ``` <container-element [ngSwitch]="switch_expression"> <some-element *ngSwitchCase="match_expression_1">...</some-element> <some-element *ngSwitchCase="match_expression_2">...</some-element> <some-other-element *ngSwitchCase="match_expression_3">...</some-other-element> <ng-container *ngSwitchCase="match_expression_3"> <!-- use a ng-container to group multiple root nodes --> <inner-element></inner-element> <inner-other-element></inner-other-element> </ng-container> <some-element *ngSwitchDefault>...</some-element> </container-element> ``` angular DATE_PIPE_DEFAULT_TIMEZONE DATE\_PIPE\_DEFAULT\_TIMEZONE ============================= `const` `deprecated` Optionally-provided default timezone to use for all instances of `[DatePipe](datepipe)` (such as `'+0430'`). If the value isn't provided, the `[DatePipe](datepipe)` will use the end-user's local system timezone. **Deprecated:** use DATE\_PIPE\_DEFAULT\_OPTIONS token to configure DatePipe ### `const DATE_PIPE_DEFAULT_TIMEZONE: InjectionToken<string>;` angular NumberSymbol NumberSymbol ============ `enum` Symbols that can be used to replace placeholders in number patterns. Examples are based on `en-US` values. See also -------- * `[getLocaleNumberSymbol](getlocalenumbersymbol)()` * [Internationalization (i18n) Guide](../../guide/i18n-overview) ``` enum NumberSymbol { Decimal Group List PercentSign PlusSign MinusSign Exponential SuperscriptingExponent PerMille Infinity NaN TimeSeparator CurrencyDecimal CurrencyGroup } ``` Members ------- | Member | Description | | --- | --- | | `Decimal` | Decimal separator. For `en-US`, the dot character. Example: 2,345`.`67 | | `Group` | Grouping separator, typically for thousands. For `en-US`, the comma character. Example: 2`,`345.67 | | `List` | List-item separator. Example: "one, two, and three" | | `PercentSign` | Sign for percentage (out of 100). Example: 23.4% | | `PlusSign` | Sign for positive numbers. Example: +23 | | `MinusSign` | Sign for negative numbers. Example: -23 | | `Exponential` | Computer notation for exponential value (n times a power of 10). Example: 1.2E3 | | `SuperscriptingExponent` | Human-readable format of exponential. Example: 1.2x103 | | `PerMille` | Sign for permille (out of 1000). Example: 23.4‰ | | `Infinity` | Infinity, can be used with plus and minus. Example: ∞, +∞, -∞ | | `NaN` | Not a number. Example: NaN | | `TimeSeparator` | Symbol used between time units. Example: 10:52 | | `CurrencyDecimal` | Decimal separator for currency values (fallback to `Decimal`). Example: $2,345.67 | | `CurrencyGroup` | Group separator for currency values (fallback to `Group`). Example: $2,345.67 | angular PRECONNECT_CHECK_BLOCKLIST PRECONNECT\_CHECK\_BLOCKLIST ============================ `const` Injection token to configure which origins should be excluded from the preconnect checks. It can either be a single string or an array of strings to represent a group of origins, for example: [See more...](preconnect_check_blocklist#description) ### `const PRECONNECT_CHECK_BLOCKLIST: InjectionToken<(string | string[])[]>;` #### Description ``` {provide: PRECONNECT_CHECK_BLOCKLIST, useValue: 'https://your-domain.com'} ``` or: ``` {provide: PRECONNECT_CHECK_BLOCKLIST, useValue: ['https://your-domain-1.com', 'https://your-domain-2.com']} ``` angular getLocaleMonthNames getLocaleMonthNames =================== `function` Retrieves months of the year for the given locale, using the Gregorian calendar. ### `getLocaleMonthNames(locale: string, formStyle: FormStyle, width: TranslationWidth): ReadonlyArray<string>` ###### Parameters | | | | | --- | --- | --- | | `locale` | `string` | A locale code for the locale format rules to use. | | `formStyle` | `[FormStyle](formstyle)` | The required grammatical form. | | `width` | `[TranslationWidth](translationwidth)` | The required character width. | ###### Returns `ReadonlyArray<string>`: An array of localized name strings. For example, `[January, February, ...]` for `en-US`. See also -------- * [Internationalization (i18n) Guide](../../guide/i18n-overview) angular DOCUMENT DOCUMENT ======== `const` A DI Token representing the main rendering context. In a browser this is the DOM Document. [See more...](document#description) ### `const DOCUMENT: InjectionToken<Document>;` #### Description Note: Document might not be available in the Application Context when Application and Rendering Contexts are not the same (e.g. when running the application in a Web Worker). angular Time Time ==== `type-alias` Represents a time value with hours and minutes. ``` type Time = { hours: number; minutes: number; }; ``` angular getNumberOfCurrencyDigits getNumberOfCurrencyDigits ========================= `function` Reports the number of decimal digits for a given currency. The value depends upon the presence of cents in that particular currency. ### `getNumberOfCurrencyDigits(code: string): number` ###### Parameters | | | | | --- | --- | --- | | `code` | `string` | The currency code. | ###### Returns `number`: The number of decimal digits, typically 0 or 2. See also -------- * [Internationalization (i18n) Guide](../../guide/i18n-overview) angular getLocalePluralCase getLocalePluralCase =================== `function` Retrieves the plural function used by ICU expressions to determine the plural case to use for a given locale. ### `getLocalePluralCase(locale: string): (value: number) => number` ###### Parameters | | | | | --- | --- | --- | | `locale` | `string` | A locale code for the locale format rules to use. | ###### Returns `(value: number) => number`: The plural function for the locale. See also -------- * `[NgPlural](ngplural)` * [Internationalization (i18n) Guide](../../guide/i18n-overview) angular NgStyle NgStyle ======= `directive` An attribute directive that updates styles for the containing HTML element. Sets one or more style properties, specified as colon-separated key-value pairs. The key is a style name, with an optional `.<unit>` suffix (such as 'top.px', 'font-style.em'). The value is an expression to be evaluated. The resulting non-null value, expressed in the given unit, is assigned to the given style property. If the result of evaluation is null, the corresponding style is removed. Exported from ------------- * [``` CommonModule ```](commonmodule) Selectors --------- * `[[ngStyle](ngstyle)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)()[ngStyle](ngstyle): { [klass: string]: any; }` | Write-Only | Description ----------- Set the font of the containing element to the result of an expression. ``` <some-element [ngStyle]="{'font-style': styleExp}">...</some-element> ``` Set the width of the containing element to a pixel value returned by an expression. ``` <some-element [ngStyle]="{'max-width.px': widthExp}">...</some-element> ``` Set a collection of style values using an expression that returns key-value pairs. ``` <some-element [ngStyle]="objExp">...</some-element> ``` Methods ------- | ngDoCheck() | | --- | | `ngDoCheck()` Parameters There are no parameters. | angular getLocaleExtraDayPeriodRules getLocaleExtraDayPeriodRules ============================ `function` Retrieves locale-specific rules used to determine which day period to use when more than one period is defined for a locale. [See more...](getlocaleextradayperiodrules#description) ### `getLocaleExtraDayPeriodRules(locale: string): (Time | [ Time, Time ])[]` ###### Parameters | | | | | --- | --- | --- | | `locale` | `string` | A locale code for the locale format rules to use. | ###### Returns `([Time](time) | [ [Time](time), [Time](time) ])[]`: The rules for the locale, a single time value or array of *from-time, to-time*, or null if no periods are available. See also -------- * `[getLocaleExtraDayPeriods](getlocaleextradayperiods)()` * [Internationalization (i18n) Guide](../../guide/i18n-overview) Description ----------- There is a rule for each defined day period. The first rule is applied to the first day period and so on. Fall back to AM/PM when no rules are available. A rule can specify a period as time range, or as a single time value. This functionality is only available when you have loaded the full locale data. See the ["I18n guide"](../../guide/i18n-common-format-data-locale).
programming_docs
angular getLocaleDayNames getLocaleDayNames ================= `function` Retrieves days of the week for the given locale, using the Gregorian calendar. ### `getLocaleDayNames(locale: string, formStyle: FormStyle, width: TranslationWidth): ReadonlyArray<string>` ###### Parameters | | | | | --- | --- | --- | | `locale` | `string` | A locale code for the locale format rules to use. | | `formStyle` | `[FormStyle](formstyle)` | The required grammatical form. | | `width` | `[TranslationWidth](translationwidth)` | The required character width. | ###### Returns `ReadonlyArray<string>`: An array of localized name strings. For example,`[Sunday, Monday, ... Saturday]` for `en-US`. See also -------- * [Internationalization (i18n) Guide](../../guide/i18n-overview) angular getLocaleDayPeriods getLocaleDayPeriods =================== `function` Retrieves day period strings for the given locale. ### `getLocaleDayPeriods(locale: string, formStyle: FormStyle, width: TranslationWidth): Readonly<[ string, string ]>` ###### Parameters | | | | | --- | --- | --- | | `locale` | `string` | A locale code for the locale format rules to use. | | `formStyle` | `[FormStyle](formstyle)` | The required grammatical form. | | `width` | `[TranslationWidth](translationwidth)` | The required character width. | ###### Returns `Readonly<[ string, string ]>`: An array of localized period strings. For example, `[AM, PM]` for `en-US`. See also -------- * [Internationalization (i18n) Guide](../../guide/i18n-overview) angular ImageLoaderConfig ImageLoaderConfig ================= `interface` Config options recognized by the image loader function. ``` interface ImageLoaderConfig { src: string width?: number } ``` See also -------- * `[ImageLoader](imageloader)` * `[NgOptimizedImage](ngoptimizedimage)` Properties ---------- | Property | Description | | --- | --- | | `src: string` | Image file name to be added to the image request URL. | | `width?: number` | Width of the requested image (to be used when generating srcset). | angular provideCloudinaryLoader provideCloudinaryLoader ======================= `const` Function that generates an ImageLoader for Cloudinary and turns it into an Angular provider. ### `const provideCloudinaryLoader: (path: string) => Provider[];` angular NgLocalization NgLocalization ============== `class` ``` abstract class NgLocalization { abstract getPluralCategory(value: any, locale?: string): string } ``` Subclasses ---------- * `[NgLocaleLocalization](nglocalelocalization)` Provided in ----------- * ``` 'root' ``` Methods ------- | getPluralCategory() | | --- | | `abstract getPluralCategory(value: any, locale?: string): string` Parameters | | | | | --- | --- | --- | | `value` | `any` | | | `locale` | `string` | Optional. Default is `undefined`. | Returns `string` | angular NumberFormatStyle NumberFormatStyle ================= `enum` Format styles that can be used to represent numbers. See also -------- * `[getLocaleNumberFormat](getlocalenumberformat)()`. * [Internationalization (i18n) Guide](../../guide/i18n-overview) ``` enum NumberFormatStyle { Decimal Percent Currency Scientific } ``` Members ------- | Member | Description | | --- | --- | | `Decimal` | | | `Percent` | | | `Currency` | | | `Scientific` | | angular @angular/common/upgrade @angular/common/upgrade ======================= `entry-point` Provides tools for upgrading from the `$location` service provided in AngularJS to Angular's [unified location service](../../guide/upgrade#using-the-unified-angular-location-service). Entry point exports ------------------- ### NgModules | | | | --- | --- | | `[LocationUpgradeModule](upgrade/locationupgrademodule)` | `[NgModule](../core/ngmodule)` used for providing and configuring Angular's Unified Location Service for upgrading. | ### Classes | | | | --- | --- | | `[$locationShim](upgrade/%24locationshim)` | Location service that provides a drop-in replacement for the $location service provided in AngularJS. | | `[$locationShimProvider](upgrade/%24locationshimprovider)` | The factory function used to create an instance of the `[$locationShim](upgrade/%24locationshim)` in Angular, and provides an API-compatible `$locationProvider` for AngularJS. | | `[AngularJSUrlCodec](upgrade/angularjsurlcodec)` | A `[UrlCodec](upgrade/urlcodec)` that uses logic from AngularJS to serialize and parse URLs and URL parameters. | | `[UrlCodec](upgrade/urlcodec)` | A codec for encoding and decoding URL parts. | ### Structures | | | | --- | --- | | `[LocationUpgradeConfig](upgrade/locationupgradeconfig)` | Configuration options for LocationUpgrade. | ### Types | | | | --- | --- | | `[LOCATION\_UPGRADE\_CONFIGURATION](upgrade/location_upgrade_configuration)` | A provider token used to configure the location upgrade module. | angular NgClass NgClass ======= `directive` Adds and removes CSS classes on an HTML element. [See more...](ngclass#description) Exported from ------------- * [``` CommonModule ```](commonmodule) Selectors --------- * `[[ngClass](ngclass)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)('class')klass: string` | Write-Only | | `@[Input](../core/input)()[ngClass](ngclass): string | string[] | Set<string> | { [klass: string]: any; }` | Write-Only | Description ----------- The CSS classes are updated as follows, depending on the type of the expression evaluation: * `string` - the CSS classes listed in the string (space delimited) are added, * `Array` - the CSS classes declared as Array elements are added, * `Object` - keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed. ``` <some-element [ngClass]="'first second'">...</some-element> <some-element [ngClass]="['first', 'second']">...</some-element> <some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element> <some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element> <some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element> ``` Methods ------- | ngDoCheck() | | --- | | `ngDoCheck(): void` Parameters There are no parameters. Returns `void` | angular CurrencyPipe CurrencyPipe ============ `pipe` Transforms a number to a currency string, formatted according to locale rules that determine group sizing and separator, decimal-point character, and other locale-specific configurations. ### `{{ value_expression | currency [ : currencyCode [ : display [ : digitsInfo [ : locale ] ] ] ] }}` #### Exported from * [``` CommonModule ```](commonmodule) Input value ----------- | | | | | --- | --- | --- | | `value` | `string | number` | The number to be formatted as currency. | Parameters ---------- | | | | | --- | --- | --- | | `currencyCode` | `string` | The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, such as `USD` for the US dollar and `EUR` for the euro. The default currency code can be configured using the `[DEFAULT\_CURRENCY\_CODE](../core/default_currency_code)` injection token. Optional. Default is `this._defaultCurrencyCode`. | | `display` | `string | boolean` | The format for the currency indicator. One of the following:* `code`: Show the code (such as `USD`). * `symbol`(default): Show the symbol (such as `$`). * `symbol-narrow`: Use the narrow symbol for locales that have two symbols for their currency. For example, the Canadian dollar CAD has the symbol `CA$` and the symbol-narrow `$`. If the locale has no narrow symbol, uses the standard symbol for the locale. * String: Use the given string value instead of a code or a symbol. For example, an empty string will suppress the currency & symbol. * Boolean (marked deprecated in v5): `true` for symbol and false for `code`. Optional. Default is `'symbol'`. | | `digitsInfo` | `string` | Decimal representation options, specified by a string in the following format: `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`.* `minIntegerDigits`: The minimum number of integer digits before the decimal point. Default is `1`. * `minFractionDigits`: The minimum number of digits after the decimal point. Default is `2`. * `maxFractionDigits`: The maximum number of digits after the decimal point. Default is `2`. If not provided, the number will be formatted with the proper amount of digits, depending on what the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) specifies. For example, the Canadian dollar has 2 digits, whereas the Chilean peso has none. Optional. Default is `undefined`. | | `locale` | `string` | A locale code for the locale format rules to use. When not supplied, uses the value of `[LOCALE\_ID](../core/locale_id)`, which is `en-US` by default. See [Setting your app locale](../../guide/i18n-common-locale-id). Optional. Default is `undefined`. | See also -------- * `[getCurrencySymbol](getcurrencysymbol)()` * `[formatCurrency](formatcurrency)()` Usage notes ----------- The following code shows how the pipe transforms numbers into text strings, according to various format specifications, where the caller's default locale is `en-US`. ``` @Component({ selector: 'currency-pipe', template: `<div> <!--output '$0.26'--> <p>A: {{a | currency}}</p> <!--output 'CA$0.26'--> <p>A: {{a | currency:'CAD'}}</p> <!--output 'CAD0.26'--> <p>A: {{a | currency:'CAD':'code'}}</p> <!--output 'CA$0,001.35'--> <p>B: {{b | currency:'CAD':'symbol':'4.2-2'}}</p> <!--output '$0,001.35'--> <p>B: {{b | currency:'CAD':'symbol-narrow':'4.2-2'}}</p> <!--output '0 001,35 CA$'--> <p>B: {{b | currency:'CAD':'symbol':'4.2-2':'fr'}}</p> <!--output 'CLP1' because CLP has no cents--> <p>B: {{b | currency:'CLP'}}</p> </div>` }) export class CurrencyPipeComponent { a: number = 0.259; b: number = 1.3495; } ``` angular @angular/common/http @angular/common/http ==================== `entry-point` Implements an HTTP client API for Angular apps that relies on the `XMLHttpRequest` interface exposed by browsers. Includes testability features, typed request and response objects, request and response interception, observable APIs, and streamlined error handling. For usage information, see the [HTTP Client](../../guide/http) guide. Entry point exports ------------------- ### NgModules | | | | --- | --- | | `[HttpClientJsonpModule](http/httpclientjsonpmodule)` | Configures the [dependency injector](../../guide/glossary#injector) for `[HttpClient](http/httpclient)` with supporting services for JSONP. Without this module, Jsonp requests reach the backend with method JSONP, where they are rejected. | | `[HttpClientModule](http/httpclientmodule)` | Configures the [dependency injector](../../guide/glossary#injector) for `[HttpClient](http/httpclient)` with supporting services for XSRF. Automatically imported by `[HttpClientModule](http/httpclientmodule)`. | | `[HttpClientXsrfModule](http/httpclientxsrfmodule)` | Configures XSRF protection support for outgoing requests. | ### Classes | | | | --- | --- | | `[HttpBackend](http/httpbackend)` | A final `[HttpHandler](http/httphandler)` which will dispatch the request via browser HTTP APIs to a backend. | | `[HttpClient](http/httpclient)` | Performs HTTP requests. This service is available as an injectable class, with methods to perform HTTP requests. Each request method has multiple signatures, and the return type varies based on the signature that is called (mainly the values of `observe` and `responseType`). | | `[HttpContext](http/httpcontext)` | Http context stores arbitrary user defined values and ensures type safety without actually knowing the types. It is backed by a `Map` and guarantees that keys do not clash. | | `[HttpContextToken](http/httpcontexttoken)` | A token used to manipulate and access values stored in `[HttpContext](http/httpcontext)`. | | `[HttpErrorResponse](http/httperrorresponse)` | A response that represents an error or failure, either from a non-successful HTTP status, an error while executing the request, or some other failure which occurred during the parsing of the response. | | `[HttpHandler](http/httphandler)` | Transforms an `[HttpRequest](http/httprequest)` into a stream of `[HttpEvent](http/httpevent)`s, one of which will likely be a `[HttpResponse](http/httpresponse)`. | | `[HttpHeaderResponse](http/httpheaderresponse)` | A partial HTTP response which only includes the status and header data, but no response body. | | `[HttpHeaders](http/httpheaders)` | Represents the header configuration options for an HTTP request. Instances are immutable. Modifying methods return a cloned instance with the change. The original object is never changed. | | `[HttpParams](http/httpparams)` | An HTTP request/response body that represents serialized parameters, per the MIME type `application/x-www-form-urlencoded`. | | `[HttpRequest](http/httprequest)` | An outgoing HTTP request with an optional typed body. | | `[HttpResponse](http/httpresponse)` | A full HTTP response, including a typed response body (which may be `null` if one was not returned). | | `[HttpResponseBase](http/httpresponsebase)` | Base class for both `[HttpResponse](http/httpresponse)` and `[HttpHeaderResponse](http/httpheaderresponse)`. | | `[HttpUrlEncodingCodec](http/httpurlencodingcodec)` | Provides encoding and decoding of URL parameter and query-string values. | | `[HttpXhrBackend](http/httpxhrbackend)` | Uses `XMLHttpRequest` to send requests to a backend server. | | `[HttpXsrfTokenExtractor](http/httpxsrftokenextractor)` | Retrieves the current XSRF token to use with the next outgoing request. | | `[JsonpClientBackend](http/jsonpclientbackend)` | Processes an `[HttpRequest](http/httprequest)` with the JSONP method, by performing JSONP style requests. | | `[JsonpInterceptor](http/jsonpinterceptor)` | Identifies requests with the method JSONP and shifts them to the `[JsonpClientBackend](http/jsonpclientbackend)`. | ### Functions | | | | --- | --- | | `[provideHttpClient](http/providehttpclient)` | Configures Angular's `[HttpClient](http/httpclient)` service to be available for injection. | | `[withInterceptors](http/withinterceptors)` | Adds one or more functional-style HTTP interceptors to the configuration of the `[HttpClient](http/httpclient)` instance. | | `[withInterceptorsFromDi](http/withinterceptorsfromdi)` | Includes class-based interceptors configured using a multi-provider in the current injector into the configured `[HttpClient](http/httpclient)` instance. | | `[withJsonpSupport](http/withjsonpsupport)` | Add JSONP support to the configuration of the current `[HttpClient](http/httpclient)` instance. | | `[withNoXsrfProtection](http/withnoxsrfprotection)` | Disables XSRF protection in the configuration of the current `[HttpClient](http/httpclient)` instance. | | `[withRequestsMadeViaParent](http/withrequestsmadeviaparent)` | Configures the current `[HttpClient](http/httpclient)` instance to make requests via the parent injector's `[HttpClient](http/httpclient)` instead of directly. | | `[withXsrfConfiguration](http/withxsrfconfiguration)` | Customizes the XSRF protection for the configuration of the current `[HttpClient](http/httpclient)` instance. | ### Structures | | | | --- | --- | | `[HttpDownloadProgressEvent](http/httpdownloadprogressevent)` | A download progress event. | | `[HttpEventType](http/httpeventtype)` | Type enumeration for the different kinds of `[HttpEvent](http/httpevent)`. | | `[HttpFeature](http/httpfeature)` | A feature for use when configuring `[provideHttpClient](http/providehttpclient)`. | | `[HttpFeatureKind](http/httpfeaturekind)` | Identifies a particular kind of `[HttpFeature](http/httpfeature)`. | | `[HttpInterceptor](http/httpinterceptor)` | Intercepts and handles an `[HttpRequest](http/httprequest)` or `[HttpResponse](http/httpresponse)`. | | `[HttpParameterCodec](http/httpparametercodec)` | A codec for encoding and decoding parameters in URLs. | | `[HttpParamsOptions](http/httpparamsoptions)` | Options used to construct an `[HttpParams](http/httpparams)` instance. | | `[HttpProgressEvent](http/httpprogressevent)` | Base interface for progress events. | | `[HttpSentEvent](http/httpsentevent)` | An event indicating that the request was sent to the server. Useful when a request may be retried multiple times, to distinguish between retries on the final event stream. | | `[HttpStatusCode](http/httpstatuscode)` | Http status codes. As per <https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml> | | `[HttpUploadProgressEvent](http/httpuploadprogressevent)` | An upload progress event. | | `[HttpUserEvent](http/httpuserevent)` | A user-defined event. | ### Types | | | | --- | --- | | `[HTTP\_INTERCEPTORS](http/http_interceptors)` | A multi-provider token that represents the array of registered `[HttpInterceptor](http/httpinterceptor)` objects. | | `[HttpEvent](http/httpevent)` | Union type for all possible events on the response stream. | | `[HttpHandlerFn](http/httphandlerfn)` | Represents the next interceptor in an interceptor chain, or the real backend if there are no further interceptors. | | `[HttpInterceptorFn](http/httpinterceptorfn)` | An interceptor for HTTP requests made via `[HttpClient](http/httpclient)`. | | `[XhrFactory](http/xhrfactory)` | **Deprecated:** `[XhrFactory](xhrfactory)` has moved, please import `[XhrFactory](xhrfactory)` from `@angular/common` instead. A wrapper around the `XMLHttpRequest` constructor. | angular XhrFactory XhrFactory ========== `class` A wrapper around the `XMLHttpRequest` constructor. ``` abstract class XhrFactory { abstract build(): XMLHttpRequest } ``` Methods ------- | build() | | --- | | `abstract build(): XMLHttpRequest` Parameters There are no parameters. Returns `XMLHttpRequest` | angular getLocaleDirection getLocaleDirection ================== `function` Retrieves the writing direction of a specified locale ### `getLocaleDirection(locale: string): 'ltr' | 'rtl'` ###### Parameters | | | | | --- | --- | --- | | `locale` | `string` | A locale code for the locale format rules to use. | ###### Returns `'ltr' | 'rtl'`: 'rtl' or 'ltr' See also -------- * [Internationalization (i18n) Guide](../../guide/i18n-overview) angular DatePipeConfig DatePipeConfig ============== `interface` An interface that describes the date pipe configuration, which can be provided using the `[DATE\_PIPE\_DEFAULT\_OPTIONS](date_pipe_default_options)` token. ``` interface DatePipeConfig { dateFormat: string timezone: string } ``` See also -------- * `[DATE\_PIPE\_DEFAULT\_OPTIONS](date_pipe_default_options)` Properties ---------- | Property | Description | | --- | --- | | `dateFormat: string` | | | `timezone: string` | | angular NgComponentOutlet NgComponentOutlet ================= `directive` Instantiates a [`Component`](../core/component) type and inserts its Host View into the current View. `[NgComponentOutlet](ngcomponentoutlet)` provides a declarative approach for dynamic component creation. [See more...](ngcomponentoutlet#description) Exported from ------------- * [``` CommonModule ```](commonmodule) Selectors --------- * `[[ngComponentOutlet](ngcomponentoutlet)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)()[ngComponentOutlet](ngcomponentoutlet): [Type](../core/type)<any> | null` | | | `@[Input](../core/input)()ngComponentOutletInjector?: [Injector](../core/injector)` | | | `@[Input](../core/input)()ngComponentOutletContent?: any[][]` | | | `@[Input](../core/input)()ngComponentOutletNgModule?: [Type](../core/type)<any>` | | | `@[Input](../core/input)()ngComponentOutletNgModuleFactory?: [NgModuleFactory](../core/ngmodulefactory)<any>` | **Deprecated** This input is deprecated, use `ngComponentOutletNgModule` instead. | Description ----------- `[NgComponentOutlet](ngcomponentoutlet)` requires a component type, if a falsy value is set the view will clear and any existing component will be destroyed. ### Fine tune control You can control the component creation process by using the following optional attributes: * `ngComponentOutletInjector`: Optional custom [`Injector`](../core/injector) that will be used as parent for the Component. Defaults to the injector of the current view container. * `ngComponentOutletContent`: Optional list of projectable nodes to insert into the content section of the component, if it exists. * `ngComponentOutletNgModule`: Optional NgModule class reference to allow loading another module dynamically, then loading a component from that module. * `ngComponentOutletNgModuleFactory`: Deprecated config option that allows providing optional NgModule factory to allow loading another module dynamically, then loading a component from that module. Use `ngComponentOutletNgModule` instead. ### Syntax Simple ``` <ng-container *ngComponentOutlet="componentTypeExpression"></ng-container> ``` Customized injector/content ``` <ng-container *ngComponentOutlet="componentTypeExpression; injector: injectorExpression; content: contentNodesExpression;"> </ng-container> ``` Customized NgModule reference ``` <ng-container *ngComponentOutlet="componentTypeExpression; ngModule: ngModuleClass;"> </ng-container> ``` ### A simple example ``` @Component({selector: 'hello-world', template: 'Hello World!'}) export class HelloWorld { } @Component({ selector: 'ng-component-outlet-simple-example', template: `<ng-container *ngComponentOutlet="HelloWorld"></ng-container>` }) export class NgComponentOutletSimpleExample { // This field is necessary to expose HelloWorld to the template. HelloWorld = HelloWorld; } ``` A more complete example with additional options: ``` @Injectable() export class Greeter { suffix = '!'; } @Component({ selector: 'complete-component', template: `Complete: <ng-content></ng-content> <ng-content></ng-content>{{ greeter.suffix }}` }) export class CompleteComponent { constructor(public greeter: Greeter) {} } @Component({ selector: 'ng-component-outlet-complete-example', template: ` <ng-container *ngComponentOutlet="CompleteComponent; injector: myInjector; content: myContent"></ng-container>` }) export class NgComponentOutletCompleteExample { // This field is necessary to expose CompleteComponent to the template. CompleteComponent = CompleteComponent; myInjector: Injector; myContent = [[document.createTextNode('Ahoj')], [document.createTextNode('Svet')]]; constructor(injector: Injector) { this.myInjector = Injector.create({providers: [{provide: Greeter, deps: []}], parent: injector}); } } ```
programming_docs
angular NgForOf NgForOf ======= `directive` A [structural directive](../../guide/structural-directives) that renders a template for each item in a collection. The directive is placed on an element, which becomes the parent of the cloned templates. [See more...](ngforof#description) See also -------- * [Structural Directives](../../guide/structural-directives) Exported from ------------- * [``` CommonModule ```](commonmodule) Selectors --------- * `[[ngFor](ngfor)][[ngForOf](ngforof)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)()[ngForOf](ngforof): U & [NgIterable](../core/ngiterable)<T>` | Write-Only The value of the iterable expression, which can be used as a [template input variable](../../guide/structural-directives#shorthand). | | `@[Input](../core/input)()ngForTrackBy: [TrackByFunction](../core/trackbyfunction)<T>` | Specifies a custom `[TrackByFunction](../core/trackbyfunction)` to compute the identity of items in an iterable. If a custom `[TrackByFunction](../core/trackbyfunction)` is not provided, `[NgForOf](ngforof)` will use the item's [object identity](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) as the key. `[NgForOf](ngforof)` uses the computed key to associate items in an iterable with DOM elements it produces for these items. A custom `[TrackByFunction](../core/trackbyfunction)` is useful to provide good user experience in cases when items in an iterable rendered using `[NgForOf](ngforof)` have a natural identifier (for example, custom ID or a primary key), and this iterable could be updated with new object instances that still represent the same underlying entity (for example, when data is re-fetched from the server, and the iterable is recreated and re-rendered, but most of the data is still the same). See also:* `[TrackByFunction](../core/trackbyfunction)` | | `@[Input](../core/input)()ngForTemplate: [TemplateRef](../core/templateref)<[NgForOfContext](ngforofcontext)<T, U>>` | Write-Only A reference to the template that is stamped out for each item in the iterable. See also:* [template reference variable](../../guide/template-reference-variables) | Description ----------- The `[ngForOf](ngforof)` directive is generally used in the [shorthand form](../../guide/structural-directives#asterisk) `*[ngFor](ngfor)`. In this form, the template to be rendered for each iteration is the content of an anchor element containing the directive. The following example shows the shorthand syntax with some options, contained in an `<li>` element. ``` <li *ngFor="let item of items; index as i; trackBy: trackByFn">...</li> ``` The shorthand form expands into a long form that uses the `[ngForOf](ngforof)` selector on an `[<ng-template>](../core/ng-template)` element. The content of the `[<ng-template>](../core/ng-template)` element is the `<li>` element that held the short-form directive. Here is the expanded version of the short-form example. ``` <ng-template ngFor let-item [ngForOf]="items" let-i="index" [ngForTrackBy]="trackByFn"> <li>...</li> </ng-template> ``` Angular automatically expands the shorthand syntax as it compiles the template. The context for each embedded view is logically merged to the current component context according to its lexical position. When using the shorthand syntax, Angular allows only [one structural directive on an element](../../guide/structural-directives#one-per-element). If you want to iterate conditionally, for example, put the `*[ngIf](ngif)` on a container element that wraps the `*[ngFor](ngfor)` element. For further discussion, see [Structural Directives](../../guide/structural-directives#one-per-element). ### Local variables `[NgForOf](ngforof)` provides exported values that can be aliased to local variables. For example: ``` <li *ngFor="let user of users; index as i; first as isFirst"> {{i}}/{{users.length}}. {{user}} <span *ngIf="isFirst">default</span> </li> ``` The following exported values can be aliased to local variables: * `$implicit: T`: The value of the individual items in the iterable (`[ngForOf](ngforof)`). * `[ngForOf](ngforof): [NgIterable](../core/ngiterable)<T>`: The value of the iterable expression. Useful when the expression is more complex then a property access, for example when using the async pipe (`userStreams | [async](asyncpipe)`). * `index: number`: The index of the current item in the iterable. * `count: number`: The length of the iterable. * `first: boolean`: True when the item is the first item in the iterable. * `last: boolean`: True when the item is the last item in the iterable. * `even: boolean`: True when the item has an even index in the iterable. * `odd: boolean`: True when the item has an odd index in the iterable. ### Change propagation When the contents of the iterator changes, `[NgForOf](ngforof)` makes the corresponding changes to the DOM: * When an item is added, a new instance of the template is added to the DOM. * When an item is removed, its template instance is removed from the DOM. * When items are reordered, their respective templates are reordered in the DOM. Angular uses object identity to track insertions and deletions within the iterator and reproduce those changes in the DOM. This has important implications for animations and any stateful controls that are present, such as `<input>` elements that accept user input. Inserted rows can be animated in, deleted rows can be animated out, and unchanged rows retain any unsaved state such as user input. For more on animations, see [Transitions and Triggers](../../guide/transition-and-triggers). The identities of elements in the iterator can change while the data does not. This can happen, for example, if the iterator is produced from an RPC to the server, and that RPC is re-run. Even if the data hasn't changed, the second response produces objects with different identities, and Angular must tear down the entire DOM and rebuild it (as if all old elements were deleted and all new elements inserted). To avoid this expensive operation, you can customize the default tracking algorithm. by supplying the `trackBy` option to `[NgForOf](ngforof)`. `trackBy` takes a function that has two arguments: `index` and `item`. If `trackBy` is given, Angular tracks changes by the return value of the function. Static methods -------------- | ngTemplateContextGuard() | | --- | | Asserts the correct type of the context for the template that `[NgForOf](ngforof)` will render. | | `static ngTemplateContextGuard<T, U extends NgIterable<T>>(dir: NgForOf<T, U>, ctx: any): ctx is NgForOfContext<T, U>` Parameters | | | | | --- | --- | --- | | `dir` | `[NgForOf](ngforof)<T, U>` | | | `ctx` | `any` | | Returns `ctx is [NgForOfContext](ngforofcontext)<T, U>` | | The presence of this method is a signal to the Ivy template type-check compiler that the `[NgForOf](ngforof)` structural directive renders its template with a specific context type. | angular getLocaleDateTimeFormat getLocaleDateTimeFormat ======================= `function` Retrieves a localized date-time formatting string. ### `getLocaleDateTimeFormat(locale: string, width: FormatWidth): string` ###### Parameters | | | | | --- | --- | --- | | `locale` | `string` | A locale code for the locale format rules to use. | | `width` | `[FormatWidth](formatwidth)` | The format type. | ###### Returns `string`: The localized formatting string. See also -------- * `[FormatWidth](formatwidth)` * [Internationalization (i18n) Guide](../../guide/i18n-overview) angular SlicePipe SlicePipe ========= `pipe` `impure` Creates a new `Array` or `String` containing a subset (slice) of the elements. ### `{{ value_expression | slice : start [ : end ] }}` #### Exported from * [``` CommonModule ```](commonmodule) Input value ----------- | | | | | --- | --- | --- | | `value` | `string | readonly T[]` | | Parameters ---------- | | | | | --- | --- | --- | | `start` | `number` | | | `end` | `number` | Optional. Default is `undefined`. | Usage notes ----------- All behavior is based on the expected behavior of the JavaScript API `Array.prototype.slice()` and `String.prototype.slice()`. When operating on an `Array`, the returned `Array` is always a copy even when all the elements are being returned. When operating on a blank value, the pipe returns the blank value. #### List Example This `[ngFor](ngfor)` example: ``` @Component({ selector: 'slice-list-pipe', template: `<ul> <li *ngFor="let i of collection | slice:1:3">{{i}}</li> </ul>` }) export class SlicePipeListComponent { collection: string[] = ['a', 'b', 'c', 'd']; } ``` produces the following: ``` <li>b</li> <li>c</li> ``` #### String Examples ``` @Component({ selector: 'slice-string-pipe', template: `<div> <p>{{str}}[0:4]: '{{str | slice:0:4}}' - output is expected to be 'abcd'</p> <p>{{str}}[4:0]: '{{str | slice:4:0}}' - output is expected to be ''</p> <p>{{str}}[-4]: '{{str | slice:-4}}' - output is expected to be 'ghij'</p> <p>{{str}}[-4:-2]: '{{str | slice:-4:-2}}' - output is expected to be 'gh'</p> <p>{{str}}[-100]: '{{str | slice:-100}}' - output is expected to be 'abcdefghij'</p> <p>{{str}}[100]: '{{str | slice:100}}' - output is expected to be ''</p> </div>` }) export class SlicePipeStringComponent { str: string = 'abcdefghij'; } ``` angular getLocaleCurrencyCode getLocaleCurrencyCode ===================== `function` Retrieves the default currency code for the given locale. [See more...](getlocalecurrencycode#description) ### `getLocaleCurrencyCode(locale: string): string | null` ###### Parameters | | | | | --- | --- | --- | | `locale` | `string` | The code of the locale whose currency code we want. | ###### Returns `string | null`: The code of the default currency for the given locale. Description ----------- The default is defined as the first currency which is still in use. angular LOCATION_INITIALIZED LOCATION\_INITIALIZED ===================== `const` Indicates when a location is initialized. ### `const LOCATION_INITIALIZED: InjectionToken<Promise<any>>;` angular getLocaleNumberFormat getLocaleNumberFormat ===================== `function` Retrieves a number format for a given locale. [See more...](getlocalenumberformat#description) ### `getLocaleNumberFormat(locale: string, type: NumberFormatStyle): string` ###### Parameters | | | | | --- | --- | --- | | `locale` | `string` | A locale code for the locale format rules to use. | | `type` | `[NumberFormatStyle](numberformatstyle)` | The type of numeric value to be formatted (such as `Decimal` or `Currency`.) | ###### Returns `string`: The localized format string. See also -------- * `[NumberFormatStyle](numberformatstyle)` * [CLDR website](http://cldr.unicode.org/translation/number-patterns) * [Internationalization (i18n) Guide](../../guide/i18n-overview) Description ----------- Numbers are formatted using patterns, like `#,###.00`. For example, the pattern `#,###.00` when used to format the number 12345.678 could result in "12'345,678". That would happen if the grouping separator for your language is an apostrophe, and the decimal separator is a comma. **Important:** The characters `.` `,` `0` `#` (and others below) are special placeholders that stand for the decimal separator, and so on, and are NOT real characters. You must NOT "translate" the placeholders. For example, don't change `.` to `,` even though in your language the decimal point is written with a comma. The symbols should be replaced by the local equivalents, using the appropriate `[NumberSymbol](numbersymbol)` for your language. Here are the special characters used in number patterns: | Symbol | Meaning | | --- | --- | | . | Replaced automatically by the character used for the decimal point. | | , | Replaced by the "grouping" (thousands) separator. | | 0 | Replaced by a digit (or zero if there aren't enough digits). | | # | Replaced by a digit (or nothing if there aren't enough). | | ¤ | Replaced by a currency symbol, such as $ or USD. | | % | Marks a percent format. The % symbol may change position, but must be retained. | | E | Marks a scientific format. The E symbol may change position, but must be retained. | | ' | Special characters used as literal characters are quoted with ASCII single quotes. | angular JsonPipe JsonPipe ======== `pipe` `impure` Converts a value into its JSON-format representation. Useful for debugging. ### `{{ value_expression | json }}` #### Exported from * [``` CommonModule ```](commonmodule) Input value ----------- | | | | | --- | --- | --- | | `value` | `any` | A value of any type to convert into a JSON-format string. | Usage notes ----------- The following component uses a JSON pipe to convert an object to JSON format, and displays the string in both formats for comparison. ``` @Component({ selector: 'json-pipe', template: `<div> <p>Without JSON pipe:</p> <pre>{{object}}</pre> <p>With JSON pipe:</p> <pre>{{object | json}}</pre> </div>` }) export class JsonPipeComponent { object: Object = {foo: 'bar', baz: 'qux', nested: {xyz: 3, numbers: [1, 2, 3, 4, 5]}}; } ``` angular NgPlural NgPlural ======== `directive` Adds / removes DOM sub-trees based on a numeric value. Tailored for pluralization. [See more...](ngplural#description) Exported from ------------- * [``` CommonModule ```](commonmodule) Selectors --------- * `[[ngPlural](ngplural)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)()[ngPlural](ngplural): number` | Write-Only | Description ----------- Displays DOM sub-trees that match the switch expression value, or failing that, DOM sub-trees that match the switch expression's pluralization category. To use this directive you must provide a container element that sets the `[[ngPlural](ngplural)]` attribute to a switch expression. Inner elements with a `[[ngPluralCase](ngpluralcase)]` will display based on their expression: * if `[[ngPluralCase](ngpluralcase)]` is set to a value starting with `=`, it will only display if the value matches the switch expression exactly, * otherwise, the view will be treated as a "category match", and will only display if exact value matches aren't found and the value maps to its category for the defined locale. See <http://cldr.unicode.org/index/cldr-spec/plural-rules> ``` <some-element [ngPlural]="value"> <ng-template ngPluralCase="=0">there is nothing</ng-template> <ng-template ngPluralCase="=1">there is one</ng-template> <ng-template ngPluralCase="few">there are a few</ng-template> </some-element> ``` Methods ------- | addCase() | | --- | | `addCase(value: string, switchView: SwitchView): void` Parameters | | | | | --- | --- | --- | | `value` | `string` | | | `switchView` | `SwitchView` | | Returns `void` | angular UpperCasePipe UpperCasePipe ============= `pipe` Transforms text to all upper case. ### `{{ value_expression | uppercase }}` #### Exported from * [``` CommonModule ```](commonmodule) Input value ----------- | | | | | --- | --- | --- | | `value` | `string` | | See also -------- * `[LowerCasePipe](lowercasepipe)` * `[TitleCasePipe](titlecasepipe)` angular getLocaleId getLocaleId =========== `function` Retrieves the locale ID from the currently loaded locale. The loaded locale could be, for example, a global one rather than a regional one. ### `getLocaleId(locale: string): string` ###### Parameters | | | | | --- | --- | --- | | `locale` | `string` | A locale code, such as `fr-FR`. | ###### Returns `string`: The locale code. For example, `fr`. See also -------- * [Internationalization (i18n) Guide](../../guide/i18n-overview) angular PopStateEvent PopStateEvent ============= `interface` ``` interface PopStateEvent { pop?: boolean state?: any type?: string url?: string } ``` Properties ---------- | Property | Description | | --- | --- | | `pop?: boolean` | | | `state?: any` | | | `type?: string` | | | `url?: string` | | angular WeekDay WeekDay ======= `enum` The value for each day of the week, based on the `en-US` locale ``` enum WeekDay { Sunday: 0 Monday Tuesday Wednesday Thursday Friday Saturday } ``` Members ------- | Member | Description | | --- | --- | | `Sunday: 0` | | | `Monday` | | | `Tuesday` | | | `Wednesday` | | | `Thursday` | | | `Friday` | | | `Saturday` | | angular Location Location ======== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A service that applications can use to interact with a browser's URL. [See more...](location#description) ``` class Location implements OnDestroy { static normalizeQueryParams: (params: string) => string static joinWithSlash: (start: string, end: string) => string static stripTrailingSlash: (url: string) => string path(includeHash: boolean = false): string getState(): unknown isCurrentPathEqualTo(path: string, query: string = ''): boolean normalize(url: string): string prepareExternalUrl(url: string): string go(path: string, query: string = '', state: any = null): void replaceState(path: string, query: string = '', state: any = null): void forward(): void back(): void historyGo(relativePosition: number = 0): void onUrlChange(fn: (url: string, state: unknown) => void): VoidFunction subscribe(onNext: (value: PopStateEvent) => void, onThrow?: (exception: any) => void, onReturn?: () => void): SubscriptionLike } ``` Subclasses ---------- * `[SpyLocation](testing/spylocation)` Provided in ----------- * ``` 'root' ``` Description ----------- Depending on the `[LocationStrategy](locationstrategy)` used, `[Location](location)` persists to the URL's path or the URL's hash segment. Further information is available in the [Usage Notes...](location#usage-notes) Static properties ----------------- | Property | Description | | --- | --- | | `[static](../upgrade/static) normalizeQueryParams: (params: string) => string` | Normalizes URL parameters by prepending with `?` if needed. | | `[static](../upgrade/static) joinWithSlash: (start: string, end: string) => string` | Joins two parts of a URL with a slash if needed. | | `[static](../upgrade/static) stripTrailingSlash: (url: string) => string` | Removes a trailing slash from a URL string if needed. Looks for the first occurrence of either `#`, `?`, or the end of the line as `/` characters and removes the trailing slash if one exists. | Methods ------- | path() | | --- | | Normalizes the URL path for this location. | | `path(includeHash: boolean = false): string` Parameters | | | | | --- | --- | --- | | `includeHash` | `boolean` | True to include an anchor fragment in the path. Optional. Default is `false`. | Returns `string`: The normalized URL path. | | getState() | | --- | | Reports the current state of the location history. | | `getState(): unknown` Parameters There are no parameters. Returns `unknown`: The current value of the `history.state` object. | | isCurrentPathEqualTo() | | --- | | Normalizes the given path and compares to the current normalized path. | | `isCurrentPathEqualTo(path: string, query: string = ''): boolean` Parameters | | | | | --- | --- | --- | | `path` | `string` | The given URL path. | | `[query](../animations/query)` | `string` | Query parameters. Optional. Default is `''`. | Returns `boolean`: True if the given URL path is equal to the current normalized path, false otherwise. | | normalize() | | --- | | Normalizes a URL path by stripping any trailing slashes. | | `normalize(url: string): string` Parameters | | | | | --- | --- | --- | | `url` | `string` | String representing a URL. | Returns `string`: The normalized URL string. | | prepareExternalUrl() | | --- | | Normalizes an external URL path. If the given URL doesn't begin with a leading slash (`'/'`), adds one before normalizing. Adds a hash if `[HashLocationStrategy](hashlocationstrategy)` is in use, or the `[APP\_BASE\_HREF](app_base_href)` if the `[PathLocationStrategy](pathlocationstrategy)` is in use. | | `prepareExternalUrl(url: string): string` Parameters | | | | | --- | --- | --- | | `url` | `string` | String representing a URL. | Returns `string`: A normalized platform-specific URL. | | go() | | --- | | Changes the browser's URL to a normalized version of a given URL, and pushes a new item onto the platform's history. | | `go(path: string, query: string = '', state: any = null): void` Parameters | | | | | --- | --- | --- | | `path` | `string` | URL path to normalize. | | `[query](../animations/query)` | `string` | Query parameters. Optional. Default is `''`. | | `state` | `any` | Location history state. Optional. Default is `null`. | Returns `void` | | replaceState() | | --- | | Changes the browser's URL to a normalized version of the given URL, and replaces the top item on the platform's history stack. | | `replaceState(path: string, query: string = '', state: any = null): void` Parameters | | | | | --- | --- | --- | | `path` | `string` | URL path to normalize. | | `[query](../animations/query)` | `string` | Query parameters. Optional. Default is `''`. | | `state` | `any` | Location history state. Optional. Default is `null`. | Returns `void` | | forward() | | --- | | Navigates forward in the platform's history. | | `forward(): void` Parameters There are no parameters. Returns `void` | | back() | | --- | | Navigates back in the platform's history. | | `back(): void` Parameters There are no parameters. Returns `void` | | historyGo() | | --- | | Navigate to a specific page from session history, identified by its relative position to the current page. See also:* <https://developer.mozilla.org/en-US/docs/Web/API/History_API#Moving_to_a_specific_point_in_history> | | `historyGo(relativePosition: number = 0): void` Parameters | | | | | --- | --- | --- | | `relativePosition` | `number` | Position of the target page in the history relative to the current page. A negative value moves backwards, a positive value moves forwards, e.g. `location.historyGo(2)` moves forward two pages and `location.historyGo(-2)` moves back two pages. When we try to go beyond what's stored in the history session, we stay in the current page. Same behaviour occurs when `relativePosition` equals 0. Optional. Default is `0`. | Returns `void` | | onUrlChange() | | --- | | Registers a URL change listener. Use to catch updates performed by the Angular framework that are not detectible through "popstate" or "hashchange" events. | | `onUrlChange(fn: (url: string, state: unknown) => void): VoidFunction` Parameters | | | | | --- | --- | --- | | `fn` | `(url: string, state: unknown) => void` | The change handler function, which take a URL and a location history state. | Returns `VoidFunction`: A function that, when executed, unregisters a URL change listener. | | subscribe() | | --- | | Subscribes to the platform's `popState` events. See also:* [onpopstate](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate) | | `subscribe(onNext: (value: PopStateEvent) => void, onThrow?: (exception: any) => void, onReturn?: () => void): SubscriptionLike` Parameters | | | | | --- | --- | --- | | `onNext` | `(value: [PopStateEvent](popstateevent)) => void` | | | `onThrow` | `(exception: any) => void` | Optional. Default is `undefined`. | | `onReturn` | `() => void` | Optional. Default is `undefined`. | Returns `SubscriptionLike`: Subscribed events. | | Note: `[Location.go()](location#go)` does not trigger the `popState` event in the browser. Use `[Location.onUrlChange()](location#onUrlChange)` to subscribe to URL changes instead. | Usage notes ----------- It's better to use the `[Router.navigate()](../router/router#navigate)` service to trigger route changes. Use `[Location](location)` only if you need to interact with or create normalized URLs outside of routing. `[Location](location)` is responsible for normalizing the URL against the application's base href. A normalized URL is absolute from the URL host, includes the application's base href, and has no trailing slash: * `/my/app/user/123` is normalized * `my/app/user/123` **is not** normalized * `/my/app/user/123/` **is not** normalized ### Example ``` import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common'; import {Component} from '@angular/core'; @Component({ selector: 'path-location', providers: [Location, {provide: LocationStrategy, useClass: PathLocationStrategy}], template: ` <h1>PathLocationStrategy</h1> Current URL is: <code>{{location.path()}}</code><br> Normalize: <code>/foo/bar/</code> is: <code>{{location.normalize('foo/bar')}}</code><br> ` }) export class PathLocationComponent { location: Location; constructor(location: Location) { this.location = location; } } ```
programming_docs
angular ViewportScroller ViewportScroller ================ `class` Defines a scroll position manager. Implemented by `BrowserViewportScroller`. ``` abstract class ViewportScroller { abstract setOffset(offset: [number, number] | (() => [number, number])): void abstract getScrollPosition(): [...] abstract scrollToPosition(position: [number, number]): void abstract scrollToAnchor(anchor: string): void abstract setHistoryScrollRestoration(scrollRestoration: "auto" | "manual"): void } ``` Provided in ----------- * ``` 'root' ``` * [``` ServerModule ```](../platform-server/servermodule) Methods ------- | setOffset() | | --- | | Configures the top offset used when scrolling to an anchor. | | `abstract setOffset(offset: [number, number] | (() => [number, number])): void` Parameters | | | | | --- | --- | --- | | `offset` | `[number, number] | (() => [number, number])` | A position in screen coordinates (a tuple with x and y values) or a function that returns the top offset position. | Returns `void` | | getScrollPosition() | | --- | | Retrieves the current scroll position. | | `abstract getScrollPosition(): [ number, number ]` Parameters There are no parameters. Returns `[ number, number ]`: A position in screen coordinates (a tuple with x and y values). | | scrollToPosition() | | --- | | Scrolls to a specified position. | | `abstract scrollToPosition(position: [number, number]): void` Parameters | | | | | --- | --- | --- | | `position` | `[number, number]` | A position in screen coordinates (a tuple with x and y values). | Returns `void` | | scrollToAnchor() | | --- | | Scrolls to an anchor element. | | `abstract scrollToAnchor(anchor: string): void` Parameters | | | | | --- | --- | --- | | `anchor` | `string` | The ID of the anchor element. | Returns `void` | | setHistoryScrollRestoration() | | --- | | Disables automatic scroll restoration provided by the browser. See also [window.history.scrollRestoration info](https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration). | | `abstract setHistoryScrollRestoration(scrollRestoration: "auto" | "manual"): void` Parameters | | | | | --- | --- | --- | | `scrollRestoration` | `"auto" | "manual"` | | Returns `void` | angular DecimalPipe DecimalPipe =========== `pipe` Formats a value according to digit options and locale rules. Locale determines group sizing and separator, decimal point character, and other locale-specific configurations. ### `{{ value_expression | number [ : digitsInfo [ : locale ] ] }}` #### Exported from * [``` CommonModule ```](commonmodule) Input value ----------- | | | | | --- | --- | --- | | `value` | `string | number` | The value to be formatted. | Parameters ---------- | | | | | --- | --- | --- | | `digitsInfo` | `string` | Sets digit and decimal representation. [See more](decimalpipe#digitsinfo). Optional. Default is `undefined`. | | `locale` | `string` | Specifies what locale format rules to use. [See more](decimalpipe#locale). Optional. Default is `undefined`. | See also -------- * `[formatNumber](formatnumber)()` Usage notes ----------- #### digitsInfo The value's decimal representation is specified by the `digitsInfo` parameter, written in the following format: ``` {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits} ``` * `minIntegerDigits`: The minimum number of integer digits before the decimal point. Default is 1. * `minFractionDigits`: The minimum number of digits after the decimal point. Default is 0. * `maxFractionDigits`: The maximum number of digits after the decimal point. Default is 3. If the formatted value is truncated it will be rounded using the "to-nearest" method: ``` {{3.6 | number: '1.0-0'}} <!--will output '4'--> {{-3.6 | number:'1.0-0'}} <!--will output '-4'--> ``` #### locale `locale` will format a value according to locale rules. Locale determines group sizing and separator, decimal point character, and other locale-specific configurations. When not supplied, uses the value of `[LOCALE\_ID](../core/locale_id)`, which is `en-US` by default. See [Setting your app locale](../../guide/i18n-common-locale-id). #### Example The following code shows how the pipe transforms values according to various format specifications, where the caller's default locale is `en-US`. ``` @Component({ selector: 'number-pipe', template: `<div> <p> No specified formatting: {{pi | number}} <!--output: '3.142'--> </p> <p> With digitsInfo parameter specified: {{pi | number:'4.1-5'}} <!--output: '0,003.14159'--> </p> <p> With digitsInfo and locale parameters specified: {{pi | number:'4.1-5':'fr'}} <!--output: '0 003,14159'--> </p> </div>` }) export class NumberPipeComponent { pi: number = 3.14159265359; } ``` angular getLocaleEraNames getLocaleEraNames ================= `function` Retrieves Gregorian-calendar eras for the given locale. ### `getLocaleEraNames(locale: string, width: TranslationWidth): Readonly<[ string, string ]>` ###### Parameters | | | | | --- | --- | --- | | `locale` | `string` | A locale code for the locale format rules to use. | | `width` | `[TranslationWidth](translationwidth)` | The required character width. | ###### Returns `Readonly<[ string, string ]>`: An array of localized era strings. For example, `[AD, BC]` for `en-US`. See also -------- * [Internationalization (i18n) Guide](../../guide/i18n-overview) angular I18nSelectPipe I18nSelectPipe ============== `pipe` Generic selector that displays the string that matches the current value. [See more...](i18nselectpipe#description) ### `{{ value_expression | i18nSelect : mapping }}` #### Exported from * [``` CommonModule ```](commonmodule) Input value ----------- | | | | | --- | --- | --- | | `value` | `string` | a string to be internationalized. | Parameters ---------- | | | | | --- | --- | --- | | `mapping` | `object` | an object that indicates the text that should be displayed for different values of the provided `value`. | Description ----------- If none of the keys of the `mapping` match the `value`, then the content of the `other` key is returned when present, otherwise an empty string is returned. Further information is available in the [Usage Notes...](i18nselectpipe#usage-notes) Usage notes ----------- #### Example ``` @Component( {selector: 'i18n-select-pipe', template: `<div>{{gender | i18nSelect: inviteMap}} </div>`}) export class I18nSelectPipeComponent { gender: string = 'male'; inviteMap: any = {'male': 'Invite him.', 'female': 'Invite her.', 'other': 'Invite them.'}; } ``` angular KeyValuePipe KeyValuePipe ============ `pipe` `impure` Transforms Object or Map into an array of key value pairs. [See more...](keyvaluepipe#description) ### `{{ input_expression | keyvalue [ : compareFn ] }}` #### Exported from * [``` CommonModule ```](commonmodule) Input value ----------- | | | | | --- | --- | --- | | `input` | `{ [key: string]: V; [key: number]: V; } | ReadonlyMap<K, V>` | | Parameters ---------- | | | | | --- | --- | --- | | `compareFn` | `(a: [KeyValue](keyvalue)<K, V>, b: [KeyValue](keyvalue)<K, V>) => number` | Optional. Default is `defaultComparator`. | Description ----------- The output array will be ordered by keys. By default the comparator will be by Unicode point value. You can optionally pass a compareFn if your keys are complex types. Further information is available in the [Usage Notes...](keyvaluepipe#usage-notes) Usage notes ----------- #### Examples This examples show how an Object or a Map can be iterated by ngFor with the use of this keyvalue pipe. ``` @Component({ selector: 'keyvalue-pipe', template: `<span> <p>Object</p> <div *ngFor="let item of object | keyvalue"> {{item.key}}:{{item.value}} </div> <p>Map</p> <div *ngFor="let item of map | keyvalue"> {{item.key}}:{{item.value}} </div> </span>` }) export class KeyValuePipeComponent { object: {[key: number]: string} = {2: 'foo', 1: 'bar'}; map = new Map([[2, 'foo'], [1, 'bar']]); } ``` angular FormatWidth FormatWidth =========== `enum` String widths available for date-time formats. The specific character widths are locale-specific. Examples are given for `en-US`. See also -------- * `[getLocaleDateFormat](getlocaledateformat)()` * `[getLocaleTimeFormat](getlocaletimeformat)()` * `[getLocaleDateTimeFormat](getlocaledatetimeformat)()` * [Internationalization (i18n) Guide](../../guide/i18n-overview) ``` enum FormatWidth { Short Medium Long Full } ``` Members ------- | Member | Description | | --- | --- | | `Short` | For `en-US`, 'M/d/yy, h:mm a'`(Example:`6/15/15, 9:03 AM`) | | `Medium` | For `en-US`, `'MMM d, y, h:mm:ss a'` (Example: `Jun 15, 2015, 9:03:01 AM`) | | `Long` | For `en-US`, `'MMMM d, y, h:mm:ss a z'` (Example: `June 15, 2015 at 9:03:01 AM GMT+1`) | | `Full` | For `en-US`, `'EEEE, MMMM d, y, h:mm:ss a zzzz'` (Example: `Monday, June 15, 2015 at 9:03:01 AM GMT+01:00`) | angular formatPercent formatPercent ============= `function` Formats a number as a percentage according to locale rules. ### `formatPercent(value: number, locale: string, digitsInfo?: string): string` ###### Parameters | | | | | --- | --- | --- | | `value` | `number` | The number to format. | | `locale` | `string` | A locale code for the locale format rules to use. | | `digitsInfo` | `string` | Decimal representation options, specified by a string in the following format: `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `[DecimalPipe](decimalpipe)` for more details. Optional. Default is `undefined`. | ###### Returns `string`: The formatted percentage value. See also -------- * `[formatNumber](formatnumber)()` * `[DecimalPipe](decimalpipe)` * [Internationalization (i18n) Guide](../../guide/i18n-overview) angular LocationChangeListener LocationChangeListener ====================== `interface` ``` interface LocationChangeListener { (event: LocationChangeEvent): any } ``` Methods ------- | *call signature* | | --- | | `(event: LocationChangeEvent): any` Parameters | | | | | --- | --- | --- | | `event` | `[LocationChangeEvent](locationchangeevent)` | | Returns `any` | angular getLocaleCurrencyName getLocaleCurrencyName ===================== `function` Retrieves the name of the currency for the main country corresponding to a given locale. For example, 'US Dollar' for `en-US`. ### `getLocaleCurrencyName(locale: string): string | null` ###### Parameters | | | | | --- | --- | --- | | `locale` | `string` | A locale code for the locale format rules to use. | ###### Returns `string | null`: The currency name, or `null` if the main country cannot be determined. See also -------- * [Internationalization (i18n) Guide](../../guide/i18n-overview) angular TitleCasePipe TitleCasePipe ============= `pipe` Transforms text to title case. Capitalizes the first letter of each word and transforms the rest of the word to lower case. Words are delimited by any whitespace character, such as a space, tab, or line-feed character. ### `{{ value_expression | titlecase }}` #### Exported from * [``` CommonModule ```](commonmodule) Input value ----------- | | | | | --- | --- | --- | | `value` | `string` | | See also -------- * `[LowerCasePipe](lowercasepipe)` * `[UpperCasePipe](uppercasepipe)` Usage notes ----------- The following example shows the result of transforming various strings into title case. ``` @Component({ selector: 'titlecase-pipe', template: `<div> <p>{{'some string' | titlecase}}</p> <!-- output is expected to be "Some String" --> <p>{{'tHIs is mIXeD CaSe' | titlecase}}</p> <!-- output is expected to be "This Is Mixed Case" --> <p>{{'it\\'s non-trivial question' | titlecase}}</p> <!-- output is expected to be "It's Non-trivial Question" --> <p>{{'one,two,three' | titlecase}}</p> <!-- output is expected to be "One,two,three" --> <p>{{'true|false' | titlecase}}</p> <!-- output is expected to be "True|false" --> <p>{{'foo-vs-bar' | titlecase}}</p> <!-- output is expected to be "Foo-vs-bar" --> </div>` }) export class TitleCasePipeComponent { } ``` angular @angular/common/testing @angular/common/testing ======================= `entry-point` Supplies infrastructure for testing functionality supplied by `@angular/common`. Entry point exports ------------------- ### Classes | | | | --- | --- | | `[MockLocationStrategy](testing/mocklocationstrategy)` | A mock implementation of [`LocationStrategy`](locationstrategy) that allows tests to fire simulated location events. | | `[MockPlatformLocation](testing/mockplatformlocation)` | Mock implementation of URL state. | | `[SpyLocation](testing/spylocation)` | A spy for [`Location`](location) that allows tests to fire simulated location events. | ### Functions | | | | --- | --- | | `[provideLocationMocks](testing/providelocationmocks)` | Returns mock providers for the `[Location](location)` and `[LocationStrategy](locationstrategy)` classes. The mocks are helpful in tests to fire simulated location events. | ### Structures | | | | --- | --- | | `[MockPlatformLocationConfig](testing/mockplatformlocationconfig)` | Mock platform location config | ### Types | | | | --- | --- | | `[MOCK\_PLATFORM\_LOCATION\_CONFIG](testing/mock_platform_location_config)` | Provider for mock platform location config | angular isPlatformWorkerApp isPlatformWorkerApp =================== `function` Returns whether a platform id represents a web worker app platform. ### `isPlatformWorkerApp(platformId: Object): boolean` ###### Parameters | | | | | --- | --- | --- | | `platformId` | `Object` | | ###### Returns `boolean` angular registerLocaleData registerLocaleData ================== `function` Register global data to be used internally by Angular. See the ["I18n guide"](../../guide/i18n-common-format-data-locale) to know how to import additional locale data. [See more...](registerlocaledata#description) ### `registerLocaleData(data: any, localeId?: any, extraData?: any): void` ###### Parameters | | | | | --- | --- | --- | | `data` | `any` | | | `localeId` | `any` | Optional. Default is `undefined`. | | `extraData` | `any` | Optional. Default is `undefined`. | ###### Returns `void` Description ----------- The signature registerLocaleData(data: any, extraData?: any) is deprecated since v5.1 angular LocationChangeEvent LocationChangeEvent =================== `interface` A serializable version of the event from `onPopState` or `onHashChange` ``` interface LocationChangeEvent { type: string state: any } ``` Properties ---------- | Property | Description | | --- | --- | | `type: string` | | | `state: any` | | angular getLocaleDateFormat getLocaleDateFormat =================== `function` Retrieves a localized date-value formatting string. ### `getLocaleDateFormat(locale: string, width: FormatWidth): string` ###### Parameters | | | | | --- | --- | --- | | `locale` | `string` | A locale code for the locale format rules to use. | | `width` | `[FormatWidth](formatwidth)` | The format type. | ###### Returns `string`: The localized formatting string. See also -------- * `[FormatWidth](formatwidth)` * [Internationalization (i18n) Guide](../../guide/i18n-overview) angular LocationStrategy LocationStrategy ================ `class` Enables the `[Location](location)` service to read route state from the browser's URL. Angular provides two strategies: `[HashLocationStrategy](hashlocationstrategy)` and `[PathLocationStrategy](pathlocationstrategy)`. [See more...](locationstrategy#description) ``` abstract class LocationStrategy { abstract path(includeHash?: boolean): string abstract prepareExternalUrl(internal: string): string abstract getState(): unknown abstract pushState(state: any, title: string, url: string, queryParams: string): void abstract replaceState(state: any, title: string, url: string, queryParams: string): void abstract forward(): void abstract back(): void historyGo(relativePosition: number)?: void abstract onPopState(fn: LocationChangeListener): void abstract getBaseHref(): string } ``` Subclasses ---------- * `[HashLocationStrategy](hashlocationstrategy)` * `[PathLocationStrategy](pathlocationstrategy)` * `[MockLocationStrategy](testing/mocklocationstrategy)` Provided in ----------- * ``` 'root' ``` Description ----------- Applications should use the `[Router](../router/router)` or `[Location](location)` services to interact with application route state. For instance, `[HashLocationStrategy](hashlocationstrategy)` produces URLs like `<http://example.com#/foo>`, and `[PathLocationStrategy](pathlocationstrategy)` produces `<http://example.com/foo>` as an equivalent URL. See these two classes for more. Methods ------- | path() | | --- | | `abstract path(includeHash?: boolean): string` Parameters | | | | | --- | --- | --- | | `includeHash` | `boolean` | Optional. Default is `undefined`. | Returns `string` | | prepareExternalUrl() | | --- | | `abstract prepareExternalUrl(internal: string): string` Parameters | | | | | --- | --- | --- | | `internal` | `string` | | Returns `string` | | getState() | | --- | | `abstract getState(): unknown` Parameters There are no parameters. Returns `unknown` | | pushState() | | --- | | `abstract pushState(state: any, title: string, url: string, queryParams: string): void` Parameters | | | | | --- | --- | --- | | `state` | `any` | | | `title` | `string` | | | `url` | `string` | | | `queryParams` | `string` | | Returns `void` | | replaceState() | | --- | | `abstract replaceState(state: any, title: string, url: string, queryParams: string): void` Parameters | | | | | --- | --- | --- | | `state` | `any` | | | `title` | `string` | | | `url` | `string` | | | `queryParams` | `string` | | Returns `void` | | forward() | | --- | | `abstract forward(): void` Parameters There are no parameters. Returns `void` | | back() | | --- | | `abstract back(): void` Parameters There are no parameters. Returns `void` | | historyGo() | | --- | | `historyGo(relativePosition: number)?: void` Parameters | | | | | --- | --- | --- | | `relativePosition` | `number` | | Returns `void` | | onPopState() | | --- | | `abstract onPopState(fn: LocationChangeListener): void` Parameters | | | | | --- | --- | --- | | `fn` | `[LocationChangeListener](locationchangelistener)` | | Returns `void` | | getBaseHref() | | --- | | `abstract getBaseHref(): string` Parameters There are no parameters. Returns `string` | angular IMAGE_CONFIG IMAGE\_CONFIG ============= `const` `[developer preview](../../guide/releases#developer-preview)` Injection token that configures the image optimized image functionality. ### `const IMAGE_CONFIG: InjectionToken<ImageConfig>;` #### See also * `[NgOptimizedImage](ngoptimizedimage)` angular getCurrencySymbol getCurrencySymbol ================= `function` Retrieves the currency symbol for a given currency code. [See more...](getcurrencysymbol#description) ### `getCurrencySymbol(code: string, format: "wide" | "narrow", locale: string = 'en'): string` ###### Parameters | | | | | --- | --- | --- | | `code` | `string` | The currency code. | | `format` | `"wide" | "narrow"` | The format, `wide` or `narrow`. | | `locale` | `string` | A locale code for the locale format rules to use. Optional. Default is `'en'`. | ###### Returns `string`: The symbol, or the currency code if no symbol is available. See also -------- * [Internationalization (i18n) Guide](../../guide/i18n-overview) Description ----------- For example, for the default `en-US` locale, the code `USD` can be represented by the narrow symbol `$` or the wide symbol `US$`.
programming_docs
angular NgOptimizedImage NgOptimizedImage ================ `directive` Directive that improves image loading performance by enforcing best practices. [See more...](ngoptimizedimage#description) Selectors --------- * `[img](ngoptimizedimage)[[ngSrc](ngoptimizedimage)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)()[ngSrc](ngoptimizedimage): string` | Name of the source image. Image name will be processed by the image loader and the final URL will be applied as the `src` property of the image. | | `@[Input](../core/input)()ngSrcset: string` | A comma separated list of width or density descriptors. The image name will be taken from `[ngSrc](ngoptimizedimage)` and combined with the list of width or density descriptors to generate the final `srcset` property of the image. Example: ``` <img ngSrc="hello.jpg" ngSrcset="100w, 200w" /> => <img src="path/hello.jpg" srcset="path/hello.jpg?w=100 100w, path/hello.jpg?w=200 200w" /> ``` | | `@[Input](../core/input)()sizes?: string` | The base `sizes` attribute passed through to the `<[img](ngoptimizedimage)>` element. Providing sizes causes the image to create an automatic responsive srcset. | | `@[Input](../core/input)()width: number | undefined` | For responsive images: the intrinsic width of the image in pixels. For fixed size images: the desired rendered width of the image in pixels. | | `@[Input](../core/input)()height: number | undefined` | For responsive images: the intrinsic height of the image in pixels. For fixed size images: the desired rendered height of the image in pixels.\* The intrinsic height of the image in pixels. | | `@[Input](../core/input)()loading?: 'lazy' | 'eager' | 'auto'` | The desired loading behavior (lazy, eager, or auto). Setting images as loading='eager' or loading='auto' marks them as non-priority images. Avoid changing this input for priority images. | | `@[Input](../core/input)()priority: boolean` | Indicates whether this image should have a high priority. | | `@[Input](../core/input)()disableOptimizedSrcset: boolean` | Disables automatic srcset generation for this image. | | `@[Input](../core/input)()fill: boolean` | `[developer preview](../../guide/releases#developer-preview)` Sets the image to "fill mode", which eliminates the height/width requirement and adds styles such that the image fills its containing element. | Description ----------- `[NgOptimizedImage](ngoptimizedimage)` ensures that the loading of the Largest Contentful Paint (LCP) image is prioritized by: * Automatically setting the `fetchpriority` attribute on the `<[img](ngoptimizedimage)>` tag * Lazy loading non-priority images by default * Asserting that there is a corresponding preconnect link tag in the document head In addition, the directive: * Generates appropriate asset URLs if a corresponding `[ImageLoader](imageloader)` function is provided * Automatically generates a srcset * Requires that `width` and `height` are set * Warns if `width` or `height` have been set incorrectly * Warns if the image will be visually distorted when rendered The `[NgOptimizedImage](ngoptimizedimage)` directive is marked as [standalone](../../guide/standalone-components) and can be imported directly. Follow the steps below to enable and use the directive: 1. Import it into the necessary NgModule or a standalone Component. 2. Optionally provide an `[ImageLoader](imageloader)` if you use an image hosting service. 3. Update the necessary `<[img](ngoptimizedimage)>` tags in templates and replace `src` attributes with `[ngSrc](ngoptimizedimage)`. Using a `[ngSrc](ngoptimizedimage)` allows the directive to control when the `src` gets set, which triggers an image download. Step 1: import the `[NgOptimizedImage](ngoptimizedimage)` directive. ``` import { NgOptimizedImage } from '@angular/common'; // Include it into the necessary NgModule @NgModule({ imports: [NgOptimizedImage], }) class AppModule {} // ... or a standalone Component @Component({ standalone: true imports: [NgOptimizedImage], }) class MyStandaloneComponent {} ``` Step 2: configure a loader. To use the **default loader**: no additional code changes are necessary. The URL returned by the generic loader will always match the value of "src". In other words, this loader applies no transformations to the resource URL and the value of the `[ngSrc](ngoptimizedimage)` attribute will be used as is. To use an existing loader for a **third-party image service**: add the provider factory for your chosen service to the `providers` array. In the example below, the Imgix loader is used: ``` import {provideImgixLoader} from '@angular/common'; // Call the function and add the result to the `providers` array: providers: [ provideImgixLoader("https://my.base.url/"), ], ``` The `[NgOptimizedImage](ngoptimizedimage)` directive provides the following functions: * `[provideCloudflareLoader](providecloudflareloader)` * `[provideCloudinaryLoader](providecloudinaryloader)` * `[provideImageKitLoader](provideimagekitloader)` * `[provideImgixLoader](provideimgixloader)` If you use a different image provider, you can create a custom loader function as described below. To use a **custom loader**: provide your loader function as a value for the `[IMAGE\_LOADER](image_loader)` DI token. ``` import {IMAGE_LOADER, ImageLoaderConfig} from '@angular/common'; // Configure the loader using the `IMAGE_LOADER` token. providers: [ { provide: IMAGE_LOADER, useValue: (config: ImageLoaderConfig) => { return `https://example.com/${config.src}-${config.width}.jpg}`; } }, ], ``` Step 3: update `<[img](ngoptimizedimage)>` tags in templates to use `[ngSrc](ngoptimizedimage)` instead of `src`. ``` <img ngSrc="logo.png" width="200" height="100"> ``` angular KeyValue KeyValue ======== `interface` A key value pair. Usually used to represent the key value pairs from a Map or Object. ``` interface KeyValue<K, V> { key: K value: V } ``` Properties ---------- | Property | Description | | --- | --- | | `key: K` | | | `value: V` | | angular LowerCasePipe LowerCasePipe ============= `pipe` Transforms text to all lower case. ### `{{ value_expression | lowercase }}` #### Exported from * [``` CommonModule ```](commonmodule) Input value ----------- | | | | | --- | --- | --- | | `value` | `string` | | See also -------- * `[UpperCasePipe](uppercasepipe)` * `[TitleCasePipe](titlecasepipe)` Usage notes ----------- The following example defines a view that allows the user to enter text, and then uses the pipe to convert the input text to all lower case. ``` @Component({ selector: 'lowerupper-pipe', template: `<div> <label>Name: </label><input #name (keyup)="change(name.value)" type="text"> <p>In lowercase: <pre>'{{value | lowercase}}'</pre> <p>In uppercase: <pre>'{{value | uppercase}}'</pre> </div>` }) export class LowerUpperPipeComponent { // TODO(issue/24571): remove '!'. value!: string; change(value: string) { this.value = value; } } ``` angular ImageLoader ImageLoader =========== `type-alias` Represents an image loader function. Image loader functions are used by the NgOptimizedImage directive to produce full image URL based on the image name and its width. ``` type ImageLoader = (config: ImageLoaderConfig) => string; ``` angular NgSwitchDefault NgSwitchDefault =============== `directive` Creates a view that is rendered when no `[NgSwitchCase](ngswitchcase)` expressions match the `[NgSwitch](ngswitch)` expression. This statement should be the final case in an `[NgSwitch](ngswitch)`. See also -------- * `[NgSwitch](ngswitch)` * `[NgSwitchCase](ngswitchcase)` Exported from ------------- * [``` CommonModule ```](commonmodule) Selectors --------- * `[[ngSwitchDefault](ngswitchdefault)]` angular getLocaleTimeFormat getLocaleTimeFormat =================== `function` Retrieves a localized time-value formatting string. ### `getLocaleTimeFormat(locale: string, width: FormatWidth): string` ###### Parameters | | | | | --- | --- | --- | | `locale` | `string` | A locale code for the locale format rules to use. | | `width` | `[FormatWidth](formatwidth)` | The format type. | ###### Returns `string`: The localized formatting string. See also -------- * `[FormatWidth](formatwidth)` * [Internationalization (i18n) Guide](../../guide/i18n-overview) angular NgFor NgFor ===== `directive` A [structural directive](../../guide/structural-directives) that renders a template for each item in a collection. The directive is placed on an element, which becomes the parent of the cloned templates. [See more...](ngfor#description) See also -------- * [Structural Directives](../../guide/structural-directives) Exported from ------------- * [``` CommonModule ```](commonmodule) Selectors --------- * `[[ngFor](ngfor)][[ngForOf](ngforof)]` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)()[ngForOf](ngforof): U & [NgIterable](../core/ngiterable)<T>` | Write-Only The value of the iterable expression, which can be used as a [template input variable](../../guide/structural-directives#shorthand). | | `@[Input](../core/input)()ngForTrackBy: [TrackByFunction](../core/trackbyfunction)<T>` | Specifies a custom `[TrackByFunction](../core/trackbyfunction)` to compute the identity of items in an iterable. If a custom `[TrackByFunction](../core/trackbyfunction)` is not provided, `[NgForOf](ngforof)` will use the item's [object identity](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) as the key. `[NgForOf](ngforof)` uses the computed key to associate items in an iterable with DOM elements it produces for these items. A custom `[TrackByFunction](../core/trackbyfunction)` is useful to provide good user experience in cases when items in an iterable rendered using `[NgForOf](ngforof)` have a natural identifier (for example, custom ID or a primary key), and this iterable could be updated with new object instances that still represent the same underlying entity (for example, when data is re-fetched from the server, and the iterable is recreated and re-rendered, but most of the data is still the same). See also:* `[TrackByFunction](../core/trackbyfunction)` | | `@[Input](../core/input)()ngForTemplate: [TemplateRef](../core/templateref)<[NgForOfContext](ngforofcontext)<T, U>>` | Write-Only A reference to the template that is stamped out for each item in the iterable. See also:* [template reference variable](../../guide/template-reference-variables) | Description ----------- The `[ngForOf](ngforof)` directive is generally used in the [shorthand form](../../guide/structural-directives#asterisk) `*[ngFor](ngfor)`. In this form, the template to be rendered for each iteration is the content of an anchor element containing the directive. The following example shows the shorthand syntax with some options, contained in an `<li>` element. ``` <li *ngFor="let item of items; index as i; trackBy: trackByFn">...</li> ``` The shorthand form expands into a long form that uses the `[ngForOf](ngforof)` selector on an `[<ng-template>](../core/ng-template)` element. The content of the `[<ng-template>](../core/ng-template)` element is the `<li>` element that held the short-form directive. Here is the expanded version of the short-form example. ``` <ng-template ngFor let-item [ngForOf]="items" let-i="index" [ngForTrackBy]="trackByFn"> <li>...</li> </ng-template> ``` Angular automatically expands the shorthand syntax as it compiles the template. The context for each embedded view is logically merged to the current component context according to its lexical position. When using the shorthand syntax, Angular allows only [one structural directive on an element](../../guide/structural-directives#one-per-element). If you want to iterate conditionally, for example, put the `*[ngIf](ngif)` on a container element that wraps the `*[ngFor](ngfor)` element. For further discussion, see [Structural Directives](../../guide/structural-directives#one-per-element). ### Local variables `[NgForOf](ngforof)` provides exported values that can be aliased to local variables. For example: ``` <li *ngFor="let user of users; index as i; first as isFirst"> {{i}}/{{users.length}}. {{user}} <span *ngIf="isFirst">default</span> </li> ``` The following exported values can be aliased to local variables: * `$implicit: T`: The value of the individual items in the iterable (`[ngForOf](ngforof)`). * `[ngForOf](ngforof): [NgIterable](../core/ngiterable)<T>`: The value of the iterable expression. Useful when the expression is more complex then a property access, for example when using the async pipe (`userStreams | [async](asyncpipe)`). * `index: number`: The index of the current item in the iterable. * `count: number`: The length of the iterable. * `first: boolean`: True when the item is the first item in the iterable. * `last: boolean`: True when the item is the last item in the iterable. * `even: boolean`: True when the item has an even index in the iterable. * `odd: boolean`: True when the item has an odd index in the iterable. ### Change propagation When the contents of the iterator changes, `[NgForOf](ngforof)` makes the corresponding changes to the DOM: * When an item is added, a new instance of the template is added to the DOM. * When an item is removed, its template instance is removed from the DOM. * When items are reordered, their respective templates are reordered in the DOM. Angular uses object identity to track insertions and deletions within the iterator and reproduce those changes in the DOM. This has important implications for animations and any stateful controls that are present, such as `<input>` elements that accept user input. Inserted rows can be animated in, deleted rows can be animated out, and unchanged rows retain any unsaved state such as user input. For more on animations, see [Transitions and Triggers](../../guide/transition-and-triggers). The identities of elements in the iterator can change while the data does not. This can happen, for example, if the iterator is produced from an RPC to the server, and that RPC is re-run. Even if the data hasn't changed, the second response produces objects with different identities, and Angular must tear down the entire DOM and rebuild it (as if all old elements were deleted and all new elements inserted). To avoid this expensive operation, you can customize the default tracking algorithm. by supplying the `trackBy` option to `[NgForOf](ngforof)`. `trackBy` takes a function that has two arguments: `index` and `item`. If `trackBy` is given, Angular tracks changes by the return value of the function. Static methods -------------- | ngTemplateContextGuard() | | --- | | Asserts the correct type of the context for the template that `[NgForOf](ngforof)` will render. | | `static ngTemplateContextGuard<T, U extends NgIterable<T>>(dir: NgForOf<T, U>, ctx: any): ctx is NgForOfContext<T, U>` Parameters | | | | | --- | --- | --- | | `dir` | `[NgForOf](ngforof)<T, U>` | | | `ctx` | `any` | | Returns `ctx is [NgForOfContext](ngforofcontext)<T, U>` | | The presence of this method is a signal to the Ivy template type-check compiler that the `[NgForOf](ngforof)` structural directive renders its template with a specific context type. | angular $locationShim $locationShim ============= `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Location service that provides a drop-in replacement for the $location service provided in AngularJS. ``` class $locationShim { constructor($injector: any, location: Location, platformLocation: PlatformLocation, urlCodec: UrlCodec, locationStrategy: LocationStrategy) onChange(fn: (url: string, state: unknown, oldUrl: string, oldState: unknown) => void, err: (e: Error) => void = (e: Error) => { }) $$parse(url: string) $$parseLinkUrl(url: string, relHref?: string): boolean absUrl(): string url(url?: string): string | this protocol(): string host(): string port(): number | null path(path?: string | number): string | this search(search?: string | number | { [key: string]: unknown; }, paramValue?: string | number | boolean | string[]): {...} hash(hash?: string | number): string | this replace(): this state(state?: unknown): unknown | this } ``` See also -------- * [Using the Angular Unified Location Service](../../../guide/upgrade#using-the-unified-angular-location-service) Constructor ----------- | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `constructor($injector: any, location: Location, platformLocation: PlatformLocation, urlCodec: UrlCodec, locationStrategy: LocationStrategy)` Parameters | | | | | --- | --- | --- | | `$injector` | `any` | | | `location` | `[Location](../location)` | | | `platformLocation` | `[PlatformLocation](../platformlocation)` | | | `urlCodec` | `[UrlCodec](urlcodec)` | | | `locationStrategy` | `[LocationStrategy](../locationstrategy)` | | | Methods ------- | onChange() | | --- | | Registers listeners for URL changes. This API is used to catch updates performed by the AngularJS framework. These changes are a subset of the `$locationChangeStart` and `$locationChangeSuccess` events which fire when AngularJS updates its internally-referenced version of the browser URL. | | `onChange(fn: (url: string, state: unknown, oldUrl: string, oldState: unknown) => void, err: (e: Error) => void = (e: Error) => { })` Parameters | | | | | --- | --- | --- | | `fn` | `(url: string, state: unknown, oldUrl: string, oldState: unknown) => void` | The callback function that is triggered for the listener when the URL changes. | | `err` | `(e: Error) => void` | The callback function that is triggered when an error occurs. Optional. Default is `(e: Error) => { }`. | | | It's possible for `$locationChange` events to happen, but for the browser URL (window.location) to remain unchanged. This `onChange` callback will fire only when AngularJS actually updates the browser URL (window.location). | | $$parse() | | --- | | Parses the provided URL, and sets the current URL to the parsed result. | | `$$parse(url: string)` Parameters | | | | | --- | --- | --- | | `url` | `string` | The URL string. | | | $$parseLinkUrl() | | --- | | Parses the provided URL and its relative URL. | | `$$parseLinkUrl(url: string, relHref?: string): boolean` Parameters | | | | | --- | --- | --- | | `url` | `string` | The full URL string. | | `relHref` | `string` | A URL string relative to the full URL string. Optional. Default is `undefined`. | Returns `boolean` | | absUrl() | | --- | | Retrieves the full URL representation with all segments encoded according to rules specified in [RFC 3986](https://tools.ietf.org/html/rfc3986). | | `absUrl(): string` Parameters There are no parameters. Returns `string` | | ``` // given URL http://example.com/#/some/path?foo=bar&baz=xoxo let absUrl = $location.absUrl(); // => "http://example.com/#/some/path?foo=bar&baz=xoxo" ``` | | url() | | --- | | Retrieves the current URL, or sets a new URL. When setting a URL, changes the path, search, and hash, and returns a reference to its own instance. `url(): string` Parameters There are no parameters. Returns `string` | | `url(url: string): this` Parameters | | | | | --- | --- | --- | | `url` | `string` | | Returns `this` | | ``` // given URL http://example.com/#/some/path?foo=bar&baz=xoxo let url = $location.url(); // => "/some/path?foo=bar&baz=xoxo" ``` | | protocol() | | --- | | Retrieves the protocol of the current URL. | | `protocol(): string` Parameters There are no parameters. Returns `string` | | ``` // given URL http://example.com/#/some/path?foo=bar&baz=xoxo let protocol = $location.protocol(); // => "http" ``` | | host() | | --- | | Retrieves the protocol of the current URL. | | `host(): string` Parameters There are no parameters. Returns `string` | | In contrast to the non-AngularJS version `location.host` which returns `hostname:port`, this returns the `hostname` portion only. ``` // given URL http://example.com/#/some/path?foo=bar&baz=xoxo let host = $location.host(); // => "example.com" // given URL http://user:[email protected]:8080/#/some/path?foo=bar&baz=xoxo host = $location.host(); // => "example.com" host = location.host; // => "example.com:8080" ``` | | port() | | --- | | Retrieves the port of the current URL. | | `port(): number | null` Parameters There are no parameters. Returns `number | null` | | ``` // given URL http://example.com/#/some/path?foo=bar&baz=xoxo let port = $location.port(); // => 80 ``` | | path() | | --- | | Retrieves the path of the current URL, or changes the path and returns a reference to its own instance. `path(): string` Parameters There are no parameters. Returns `string` | | `path(path: string | number): this` Parameters | | | | | --- | --- | --- | | `path` | `string | number` | | Returns `this` | | Paths should always begin with forward slash (/). This method adds the forward slash if it is missing. ``` // given URL http://example.com/#/some/path?foo=bar&baz=xoxo let path = $location.path(); // => "/some/path" ``` | | search() | | --- | | 3 overloads... Show All Hide All Overload #1 Retrieves a map of the search parameters of the current URL, or changes a search part and returns a reference to its own instance. `search(): { [key: string]: unknown; }` Parameters There are no parameters. Returns `{ }`: The parsed` search`object of the current URL, or the changed`search` object. Overload #2 `search(search: string | number | { [key: string]: unknown; }): this` Parameters | | | | | --- | --- | --- | | `search` | `string | number | { [key: string]: unknown; }` | | Returns `this` Overload #3 `search(search: string | number | { [key: string]: unknown; }, paramValue: string | number | boolean | string[]): this` Parameters | | | | | --- | --- | --- | | `search` | `string | number | { [key: string]: unknown; }` | | | `paramValue` | `string | number | boolean | string[]` | | Returns `this` | | ``` // given URL http://example.com/#/some/path?foo=bar&baz=xoxo let searchObject = $location.search(); // => {foo: 'bar', baz: 'xoxo'} // set foo to 'yipee' $location.search('foo', 'yipee'); // $location.search() => {foo: 'yipee', baz: 'xoxo'} ``` | | hash() | | --- | | Retrieves the current hash fragment, or changes the hash fragment and returns a reference to its own instance. `hash(): string` Parameters There are no parameters. Returns `string` | | `hash(hash: string | number): this` Parameters | | | | | --- | --- | --- | | `hash` | `string | number` | | Returns `this` | | ``` // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue let hash = $location.hash(); // => "hashValue" ``` | | replace() | | --- | | Changes to `$location` during the current `$digest` will replace the current history record, instead of adding a new one. | | `replace(): this` Parameters There are no parameters. Returns `this` | | state() | | --- | | Retrieves the history state object when called without any parameter. `state(): unknown` Parameters There are no parameters. Returns `unknown` | | `state(state: unknown): this` Parameters | | | | | --- | --- | --- | | `state` | `unknown` | | Returns `this` | | Change the history state object when called with one parameter and return `$location`. The state object is later passed to `pushState` or `replaceState`. This method is supported only in HTML5 mode and only in browsers supporting the HTML5 History API methods such as `pushState` and `replaceState`. If you need to support older browsers (like Android < 4.0), don't use this method. |
programming_docs
angular $locationShimProvider $locationShimProvider ===================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` The factory function used to create an instance of the `[$locationShim](%24locationshim)` in Angular, and provides an API-compatible `$locationProvider` for AngularJS. ``` class $locationShimProvider { constructor(ngUpgrade: UpgradeModule, location: Location, platformLocation: PlatformLocation, urlCodec: UrlCodec, locationStrategy: LocationStrategy) $get() hashPrefix(prefix?: string) html5Mode(mode?: any) } ``` Constructor ----------- | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `constructor(ngUpgrade: UpgradeModule, location: Location, platformLocation: PlatformLocation, urlCodec: UrlCodec, locationStrategy: LocationStrategy)` Parameters | | | | | --- | --- | --- | | `ngUpgrade` | `[UpgradeModule](../../upgrade/static/upgrademodule)` | | | `location` | `[Location](../location)` | | | `platformLocation` | `[PlatformLocation](../platformlocation)` | | | `urlCodec` | `[UrlCodec](urlcodec)` | | | `locationStrategy` | `[LocationStrategy](../locationstrategy)` | | | Methods ------- | $get() | | --- | | Factory method that returns an instance of the $locationShim | | `$get()` Parameters There are no parameters. | | hashPrefix() | | --- | | Stub method used to keep API compatible with AngularJS. This setting is configured through the LocationUpgradeModule's `config` method in your Angular app. | | `hashPrefix(prefix?: string)` Parameters | | | | | --- | --- | --- | | `prefix` | `string` | Optional. Default is `undefined`. | | | html5Mode() | | --- | | Stub method used to keep API compatible with AngularJS. This setting is configured through the LocationUpgradeModule's `config` method in your Angular app. | | `html5Mode(mode?: any)` Parameters | | | | | --- | --- | --- | | `mode` | `any` | Optional. Default is `undefined`. | | angular LocationUpgradeModule LocationUpgradeModule ===================== `ngmodule` `[NgModule](../../core/ngmodule)` used for providing and configuring Angular's Unified Location Service for upgrading. ``` class LocationUpgradeModule { static config(config?: LocationUpgradeConfig): ModuleWithProviders<LocationUpgradeModule> } ``` See also -------- * [Using the Unified Angular Location Service](../../../guide/upgrade#using-the-unified-angular-location-service) Static methods -------------- | config() | | --- | | `static config(config?: LocationUpgradeConfig): ModuleWithProviders<LocationUpgradeModule>` Parameters | | | | | --- | --- | --- | | `config` | `[LocationUpgradeConfig](locationupgradeconfig)` | Optional. Default is `undefined`. | Returns `[ModuleWithProviders](../../core/modulewithproviders)<[LocationUpgradeModule](locationupgrademodule)>` | angular LocationUpgradeConfig LocationUpgradeConfig ===================== `interface` Configuration options for LocationUpgrade. ``` interface LocationUpgradeConfig { useHash?: boolean hashPrefix?: string urlCodec?: typeof UrlCodec serverBaseHref?: string appBaseHref?: string } ``` Properties ---------- | Property | Description | | --- | --- | | `useHash?: boolean` | Configures whether the location upgrade module should use the `[HashLocationStrategy](../hashlocationstrategy)` or the `[PathLocationStrategy](../pathlocationstrategy)` | | `hashPrefix?: string` | Configures the hash prefix used in the URL when using the `[HashLocationStrategy](../hashlocationstrategy)` | | `urlCodec?: typeof [UrlCodec](urlcodec)` | Configures the URL codec for encoding and decoding URLs. Default is the `AngularJSCodec` | | `serverBaseHref?: string` | Configures the base href when used in server-side rendered applications | | `appBaseHref?: string` | Configures the base href when used in client-side rendered applications | angular LOCATION_UPGRADE_CONFIGURATION LOCATION\_UPGRADE\_CONFIGURATION ================================ `const` A provider token used to configure the location upgrade module. ### `const LOCATION_UPGRADE_CONFIGURATION: InjectionToken<LocationUpgradeConfig>;` angular UrlCodec UrlCodec ======== `class` A codec for encoding and decoding URL parts. ``` abstract class UrlCodec { abstract encodePath(path: string): string abstract decodePath(path: string): string abstract encodeSearch(search: string | { [k: string]: unknown; }): string abstract decodeSearch(search: string): {...} abstract encodeHash(hash: string): string abstract decodeHash(hash: string): string abstract normalize(href: string): string abstract areEqual(valA: string, valB: string): boolean abstract parse(url: string, base?: string): {...} } ``` Subclasses ---------- * `[AngularJSUrlCodec](angularjsurlcodec)` Methods ------- | encodePath() | | --- | | Encodes the path from the provided string | | `abstract encodePath(path: string): string` Parameters | | | | | --- | --- | --- | | `path` | `string` | The path string | Returns `string` | | decodePath() | | --- | | Decodes the path from the provided string | | `abstract decodePath(path: string): string` Parameters | | | | | --- | --- | --- | | `path` | `string` | The path string | Returns `string` | | encodeSearch() | | --- | | Encodes the search string from the provided string or object | | `abstract encodeSearch(search: string | { [k: string]: unknown; }): string` Parameters | | | | | --- | --- | --- | | `search` | `string | { [k: string]: unknown; }` | | Returns `string` | | decodeSearch() | | --- | | Decodes the search objects from the provided string | | `abstract decodeSearch(search: string): { [k: string]: unknown; }` Parameters | | | | | --- | --- | --- | | `search` | `string` | | Returns `{ }` | | encodeHash() | | --- | | Encodes the hash from the provided string | | `abstract encodeHash(hash: string): string` Parameters | | | | | --- | --- | --- | | `hash` | `string` | | Returns `string` | | decodeHash() | | --- | | Decodes the hash from the provided string | | `abstract decodeHash(hash: string): string` Parameters | | | | | --- | --- | --- | | `hash` | `string` | | Returns `string` | | normalize() | | --- | | Normalizes the URL from the provided string | | `abstract normalize(href: string): string` Parameters | | | | | --- | --- | --- | | `href` | `string` | | Returns `string` | | Normalizes the URL from the provided string, search, hash, and base URL parameters `abstract normalize(path: string, search: { [k: string]: unknown; }, hash: string, baseUrl?: string): string` Parameters | | | | | --- | --- | --- | | `path` | `string` | The URL path | | `search` | `object` | The search object | | `hash` | `string` | The has string | | `baseUrl` | `string` | The base URL for the URL Optional. Default is `undefined`. | Returns `string` | | areEqual() | | --- | | Checks whether the two strings are equal | | `abstract areEqual(valA: string, valB: string): boolean` Parameters | | | | | --- | --- | --- | | `valA` | `string` | First string for comparison | | `valB` | `string` | Second string for comparison | Returns `boolean` | | parse() | | --- | | Parses the URL string based on the base URL | | `abstract parse(url: string, base?: string): { href: string; protocol: string; host: string; search: string; hash: string; hostname: string; port: string; pathname: string; }` Parameters | | | | | --- | --- | --- | | `url` | `string` | The full URL string | | `base` | `string` | The base for the URL Optional. Default is `undefined`. | Returns `{ href: string; protocol: string; host: string; search: string; hash: string; hostname: string; port: string; pathname: string; }` | angular AngularJSUrlCodec AngularJSUrlCodec ================= `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A `[UrlCodec](urlcodec)` that uses logic from AngularJS to serialize and parse URLs and URL parameters. ``` class AngularJSUrlCodec implements UrlCodec { encodePath(path: string): string encodeSearch(search: string | { [k: string]: unknown; }): string encodeHash(hash: string) decodePath(path: string, html5Mode: boolean = true): string decodeSearch(search: string) decodeHash(hash: string) normalize(pathOrHref: string, search?: { [k: string]: unknown; }, hash?: string, baseUrl?: string): string areEqual(valA: string, valB: string) parse(url: string, base?: string) } ``` Methods ------- | encodePath() | | --- | | `encodePath(path: string): string` Parameters | | | | | --- | --- | --- | | `path` | `string` | | Returns `string` | | encodeSearch() | | --- | | `encodeSearch(search: string | { [k: string]: unknown; }): string` Parameters | | | | | --- | --- | --- | | `search` | `string | { [k: string]: unknown; }` | | Returns `string` | | encodeHash() | | --- | | `encodeHash(hash: string)` Parameters | | | | | --- | --- | --- | | `hash` | `string` | | | | decodePath() | | --- | | `decodePath(path: string, html5Mode: boolean = true): string` Parameters | | | | | --- | --- | --- | | `path` | `string` | | | `html5Mode` | `boolean` | Optional. Default is `true`. | Returns `string` | | decodeSearch() | | --- | | `decodeSearch(search: string)` Parameters | | | | | --- | --- | --- | | `search` | `string` | | | | decodeHash() | | --- | | `decodeHash(hash: string)` Parameters | | | | | --- | --- | --- | | `hash` | `string` | | | | normalize() | | --- | | `normalize(href: string): string` Parameters | | | | | --- | --- | --- | | `href` | `string` | | Returns `string` | | `normalize(path: string, search: { [k: string]: unknown; }, hash: string, baseUrl?: string): string` Parameters | | | | | --- | --- | --- | | `path` | `string` | | | `search` | `object` | | | `hash` | `string` | | | `baseUrl` | `string` | Optional. Default is `undefined`. | Returns `string` | | areEqual() | | --- | | `areEqual(valA: string, valB: string)` Parameters | | | | | --- | --- | --- | | `valA` | `string` | | | `valB` | `string` | | | | parse() | | --- | | `parse(url: string, base?: string)` Parameters | | | | | --- | --- | --- | | `url` | `string` | | | `base` | `string` | Optional. Default is `undefined`. | | angular MOCK_PLATFORM_LOCATION_CONFIG MOCK\_PLATFORM\_LOCATION\_CONFIG ================================ `const` Provider for mock platform location config ### `const MOCK_PLATFORM_LOCATION_CONFIG: InjectionToken<MockPlatformLocationConfig>;` angular provideLocationMocks provideLocationMocks ==================== `function` Returns mock providers for the `[Location](../location)` and `[LocationStrategy](../locationstrategy)` classes. The mocks are helpful in tests to fire simulated location events. ### `provideLocationMocks(): Provider[]` ###### Parameters There are no parameters. ###### Returns `[Provider](../../core/provider)[]` angular MockPlatformLocation MockPlatformLocation ==================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Mock implementation of URL state. ``` class MockPlatformLocation implements PlatformLocation { hostname protocol port pathname search hash state href: string url: string getBaseHrefFromDOM(): string onPopState(fn: LocationChangeListener): VoidFunction onHashChange(fn: LocationChangeListener): VoidFunction replaceState(state: any, title: string, newUrl: string): void pushState(state: any, title: string, newUrl: string): void forward(): void back(): void historyGo(relativePosition: number = 0): void getState(): unknown } ``` Properties ---------- | Property | Description | | --- | --- | | `hostname` | Read-Only | | `protocol` | Read-Only | | `port` | Read-Only | | `pathname` | Read-Only | | `search` | Read-Only | | `hash` | Read-Only | | `state` | Read-Only | | `href: string` | Read-Only | | `url: string` | Read-Only | Methods ------- | getBaseHrefFromDOM() | | --- | | `getBaseHrefFromDOM(): string` Parameters There are no parameters. Returns `string` | | onPopState() | | --- | | `onPopState(fn: LocationChangeListener): VoidFunction` Parameters | | | | | --- | --- | --- | | `fn` | `[LocationChangeListener](../locationchangelistener)` | | Returns `VoidFunction` | | onHashChange() | | --- | | `onHashChange(fn: LocationChangeListener): VoidFunction` Parameters | | | | | --- | --- | --- | | `fn` | `[LocationChangeListener](../locationchangelistener)` | | Returns `VoidFunction` | | replaceState() | | --- | | `replaceState(state: any, title: string, newUrl: string): void` Parameters | | | | | --- | --- | --- | | `state` | `any` | | | `title` | `string` | | | `newUrl` | `string` | | Returns `void` | | pushState() | | --- | | `pushState(state: any, title: string, newUrl: string): void` Parameters | | | | | --- | --- | --- | | `state` | `any` | | | `title` | `string` | | | `newUrl` | `string` | | Returns `void` | | forward() | | --- | | `forward(): void` Parameters There are no parameters. Returns `void` | | back() | | --- | | `back(): void` Parameters There are no parameters. Returns `void` | | historyGo() | | --- | | `historyGo(relativePosition: number = 0): void` Parameters | | | | | --- | --- | --- | | `relativePosition` | `number` | Optional. Default is `0`. | Returns `void` | | getState() | | --- | | `getState(): unknown` Parameters There are no parameters. Returns `unknown` | angular SpyLocation SpyLocation =========== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A spy for [`Location`](../location) that allows tests to fire simulated location events. ``` class SpyLocation implements Location { urlChanges: string[] ngOnDestroy(): void setInitialPath(url: string) setBaseHref(url: string) path(): string getState(): unknown isCurrentPathEqualTo(path: string, query: string = ''): boolean simulateUrlPop(pathname: string) simulateHashChange(pathname: string) prepareExternalUrl(url: string): string go(path: string, query: string = '', state: any = null) replaceState(path: string, query: string = '', state: any = null) forward() back() historyGo(relativePosition: number = 0): void onUrlChange(fn: (url: string, state: unknown) => void): VoidFunction subscribe(onNext: (value: any) => void, onThrow?: (error: any) => void, onReturn?: () => void): SubscriptionLike normalize(url: string): string } ``` Properties ---------- | Property | Description | | --- | --- | | `urlChanges: string[]` | | Methods ------- | ngOnDestroy() | | --- | | `ngOnDestroy(): void` Parameters There are no parameters. Returns `void` | | setInitialPath() | | --- | | `setInitialPath(url: string)` Parameters | | | | | --- | --- | --- | | `url` | `string` | | | | setBaseHref() | | --- | | `setBaseHref(url: string)` Parameters | | | | | --- | --- | --- | | `url` | `string` | | | | path() | | --- | | `path(): string` Parameters There are no parameters. Returns `string` | | getState() | | --- | | `getState(): unknown` Parameters There are no parameters. Returns `unknown` | | isCurrentPathEqualTo() | | --- | | `isCurrentPathEqualTo(path: string, query: string = ''): boolean` Parameters | | | | | --- | --- | --- | | `path` | `string` | | | `[query](../../animations/query)` | `string` | Optional. Default is `''`. | Returns `boolean` | | simulateUrlPop() | | --- | | `simulateUrlPop(pathname: string)` Parameters | | | | | --- | --- | --- | | `pathname` | `string` | | | | simulateHashChange() | | --- | | `simulateHashChange(pathname: string)` Parameters | | | | | --- | --- | --- | | `pathname` | `string` | | | | prepareExternalUrl() | | --- | | `prepareExternalUrl(url: string): string` Parameters | | | | | --- | --- | --- | | `url` | `string` | | Returns `string` | | go() | | --- | | `go(path: string, query: string = '', state: any = null)` Parameters | | | | | --- | --- | --- | | `path` | `string` | | | `[query](../../animations/query)` | `string` | Optional. Default is `''`. | | `state` | `any` | Optional. Default is `null`. | | | replaceState() | | --- | | `replaceState(path: string, query: string = '', state: any = null)` Parameters | | | | | --- | --- | --- | | `path` | `string` | | | `[query](../../animations/query)` | `string` | Optional. Default is `''`. | | `state` | `any` | Optional. Default is `null`. | | | forward() | | --- | | `forward()` Parameters There are no parameters. | | back() | | --- | | `back()` Parameters There are no parameters. | | historyGo() | | --- | | `historyGo(relativePosition: number = 0): void` Parameters | | | | | --- | --- | --- | | `relativePosition` | `number` | Optional. Default is `0`. | Returns `void` | | onUrlChange() | | --- | | `onUrlChange(fn: (url: string, state: unknown) => void): VoidFunction` Parameters | | | | | --- | --- | --- | | `fn` | `(url: string, state: unknown) => void` | | Returns `VoidFunction` | | subscribe() | | --- | | `subscribe(onNext: (value: any) => void, onThrow?: (error: any) => void, onReturn?: () => void): SubscriptionLike` Parameters | | | | | --- | --- | --- | | `onNext` | `(value: any) => void` | | | `onThrow` | `(error: any) => void` | Optional. Default is `undefined`. | | `onReturn` | `() => void` | Optional. Default is `undefined`. | Returns `SubscriptionLike` | | normalize() | | --- | | `normalize(url: string): string` Parameters | | | | | --- | --- | --- | | `url` | `string` | | Returns `string` | angular MockPlatformLocationConfig MockPlatformLocationConfig ========================== `interface` Mock platform location config ``` interface MockPlatformLocationConfig { startUrl?: string appBaseHref?: string } ``` Properties ---------- | Property | Description | | --- | --- | | `startUrl?: string` | | | `appBaseHref?: string` | | angular MockLocationStrategy MockLocationStrategy ==================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A mock implementation of [`LocationStrategy`](../locationstrategy) that allows tests to fire simulated location events. ``` class MockLocationStrategy extends LocationStrategy { internalBaseHref: string internalPath: string internalTitle: string urlChanges: string[] simulatePopState(url: string): void path(includeHash: boolean = false): string prepareExternalUrl(internal: string): string pushState(ctx: any, title: string, path: string, query: string): void replaceState(ctx: any, title: string, path: string, query: string): void onPopState(fn: (value: any) => void): void getBaseHref(): string back(): void forward(): void getState(): unknown // inherited from common/LocationStrategy abstract path(includeHash?: boolean): string abstract prepareExternalUrl(internal: string): string abstract getState(): unknown abstract pushState(state: any, title: string, url: string, queryParams: string): void abstract replaceState(state: any, title: string, url: string, queryParams: string): void abstract forward(): void abstract back(): void historyGo(relativePosition: number)?: void abstract onPopState(fn: LocationChangeListener): void abstract getBaseHref(): string } ``` Properties ---------- | Property | Description | | --- | --- | | `internalBaseHref: string` | | | `internalPath: string` | | | `internalTitle: string` | | | `urlChanges: string[]` | | Methods ------- | simulatePopState() | | --- | | `simulatePopState(url: string): void` Parameters | | | | | --- | --- | --- | | `url` | `string` | | Returns `void` | | path() | | --- | | `path(includeHash: boolean = false): string` Parameters | | | | | --- | --- | --- | | `includeHash` | `boolean` | Optional. Default is `false`. | Returns `string` | | prepareExternalUrl() | | --- | | `prepareExternalUrl(internal: string): string` Parameters | | | | | --- | --- | --- | | `internal` | `string` | | Returns `string` | | pushState() | | --- | | `pushState(ctx: any, title: string, path: string, query: string): void` Parameters | | | | | --- | --- | --- | | `ctx` | `any` | | | `title` | `string` | | | `path` | `string` | | | `[query](../../animations/query)` | `string` | | Returns `void` | | replaceState() | | --- | | `replaceState(ctx: any, title: string, path: string, query: string): void` Parameters | | | | | --- | --- | --- | | `ctx` | `any` | | | `title` | `string` | | | `path` | `string` | | | `[query](../../animations/query)` | `string` | | Returns `void` | | onPopState() | | --- | | `onPopState(fn: (value: any) => void): void` Parameters | | | | | --- | --- | --- | | `fn` | `(value: any) => void` | | Returns `void` | | getBaseHref() | | --- | | `getBaseHref(): string` Parameters There are no parameters. Returns `string` | | back() | | --- | | `back(): void` Parameters There are no parameters. Returns `void` | | forward() | | --- | | `forward(): void` Parameters There are no parameters. Returns `void` | | getState() | | --- | | `getState(): unknown` Parameters There are no parameters. Returns `unknown` |
programming_docs
angular HttpErrorResponse HttpErrorResponse ================= `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A response that represents an error or failure, either from a non-successful HTTP status, an error while executing the request, or some other failure which occurred during the parsing of the response. [See more...](httperrorresponse#description) ``` class HttpErrorResponse extends HttpResponseBase implements Error { constructor(init: { error?: any; headers?: HttpHeaders; status?: number; statusText?: string; url?: string; }) name: 'HttpErrorResponse' message: string error: any | null ok: false // inherited from common/http/HttpResponseBase constructor(init: { headers?: HttpHeaders; status?: number; statusText?: string; url?: string; }, defaultStatus: number = HttpStatusCode.Ok, defaultStatusText: string = 'OK') headers: HttpHeaders status: number statusText: string url: string | null ok: boolean type: HttpEventType.Response | HttpEventType.ResponseHeader } ``` Description ----------- Any error returned on the `Observable` response stream will be wrapped in an `[HttpErrorResponse](httperrorresponse)` to provide additional context about the state of the HTTP layer when the error occurred. The error property will contain either a wrapped Error object or the error response returned from the server. Constructor ----------- | | | | | | --- | --- | --- | --- | | `constructor(init: { error?: any; headers?: HttpHeaders; status?: number; statusText?: string; url?: string; })` Parameters | | | | | --- | --- | --- | | `init` | `object` | | | Properties ---------- | Property | Description | | --- | --- | | `name: '[HttpErrorResponse](httperrorresponse)'` | Read-Only | | `message: string` | Read-Only | | `error: any | null` | Read-Only | | `ok: false` | Read-Only Errors are never okay, even when the status code is in the 2xx success range. | angular HttpBackend HttpBackend =========== `class` A final `[HttpHandler](httphandler)` which will dispatch the request via browser HTTP APIs to a backend. [See more...](httpbackend#description) ``` abstract class HttpBackend implements HttpHandler { abstract handle(req: HttpRequest<any>): Observable<HttpEvent<any>> } ``` Subclasses ---------- * `[JsonpClientBackend](jsonpclientbackend)` * `[HttpXhrBackend](httpxhrbackend)` Description ----------- Interceptors sit between the `[HttpClient](httpclient)` interface and the `[HttpBackend](httpbackend)`. When injected, `[HttpBackend](httpbackend)` dispatches requests directly to the backend, without going through the interceptor chain. Methods ------- | handle() | | --- | | `abstract handle(req: HttpRequest<any>): Observable<HttpEvent<any>>` Parameters | | | | | --- | --- | --- | | `req` | `[HttpRequest](httprequest)<any>` | | Returns `Observable<[HttpEvent](httpevent)<any>>` | angular withInterceptorsFromDi withInterceptorsFromDi ====================== `function` Includes class-based interceptors configured using a multi-provider in the current injector into the configured `[HttpClient](httpclient)` instance. [See more...](withinterceptorsfromdi#description) ### `withInterceptorsFromDi(): HttpFeature<HttpFeatureKind.LegacyInterceptors>` ###### Parameters There are no parameters. ###### Returns `[HttpFeature](httpfeature)<[HttpFeatureKind.LegacyInterceptors](httpfeaturekind#LegacyInterceptors)>` See also -------- * HttpInterceptor * HTTP\_INTERCEPTORS * provideHttpClient Description ----------- Prefer `[withInterceptors](withinterceptors)` and functional interceptors instead, as support for DI-provided interceptors may be phased out in a later release. angular HttpProgressEvent HttpProgressEvent ================= `interface` Base interface for progress events. ``` interface HttpProgressEvent { type: HttpEventType.DownloadProgress | HttpEventType.UploadProgress loaded: number total?: number } ``` Child interfaces ---------------- * `[HttpDownloadProgressEvent](httpdownloadprogressevent)` * `[HttpUploadProgressEvent](httpuploadprogressevent)` Properties ---------- | Property | Description | | --- | --- | | `type: [HttpEventType.DownloadProgress](httpeventtype#DownloadProgress) | [HttpEventType.UploadProgress](httpeventtype#UploadProgress)` | Progress event type is either upload or download. | | `loaded: number` | Number of bytes uploaded or downloaded. | | `total?: number` | Total number of bytes to upload or download. Depending on the request or response, this may not be computable and thus may not be present. | angular withInterceptors withInterceptors ================ `function` Adds one or more functional-style HTTP interceptors to the configuration of the `[HttpClient](httpclient)` instance. ### `withInterceptors(interceptorFns: HttpInterceptorFn[]): HttpFeature<HttpFeatureKind.Interceptors>` ###### Parameters | | | | | --- | --- | --- | | `interceptorFns` | `[HttpInterceptorFn](httpinterceptorfn)[]` | | ###### Returns `[HttpFeature](httpfeature)<[HttpFeatureKind.Interceptors](httpfeaturekind#Interceptors)>` See also -------- * HttpInterceptorFn * provideHttpClient angular HttpParameterCodec HttpParameterCodec ================== `interface` A codec for encoding and decoding parameters in URLs. [See more...](httpparametercodec#description) ``` interface HttpParameterCodec { encodeKey(key: string): string encodeValue(value: string): string decodeKey(key: string): string decodeValue(value: string): string } ``` Class implementations --------------------- * `[HttpUrlEncodingCodec](httpurlencodingcodec)` Description ----------- Used by `[HttpParams](httpparams)`. Methods ------- | encodeKey() | | --- | | `encodeKey(key: string): string` Parameters | | | | | --- | --- | --- | | `key` | `string` | | Returns `string` | | encodeValue() | | --- | | `encodeValue(value: string): string` Parameters | | | | | --- | --- | --- | | `value` | `string` | | Returns `string` | | decodeKey() | | --- | | `decodeKey(key: string): string` Parameters | | | | | --- | --- | --- | | `key` | `string` | | Returns `string` | | decodeValue() | | --- | | `decodeValue(value: string): string` Parameters | | | | | --- | --- | --- | | `value` | `string` | | Returns `string` | angular HttpEvent HttpEvent ========= `type-alias` Union type for all possible events on the response stream. [See more...](httpevent#description) ``` type HttpEvent<T> = HttpSentEvent | HttpHeaderResponse | HttpResponse<T> | HttpProgressEvent | HttpUserEvent<T>; ``` Description ----------- Typed according to the expected type of the response. angular HttpParams HttpParams ========== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An HTTP request/response body that represents serialized parameters, per the MIME type `application/x-www-form-urlencoded`. [See more...](httpparams#description) ``` class HttpParams { constructor(options: HttpParamsOptions = {} as HttpParamsOptions) has(param: string): boolean get(param: string): string | null getAll(param: string): string[] | null keys(): string[] append(param: string, value: string | number | boolean): HttpParams appendAll(params: { [param: string]: string | number | boolean | readonly (string | number | boolean)[]; }): HttpParams set(param: string, value: string | number | boolean): HttpParams delete(param: string, value?: string | number | boolean): HttpParams toString(): string } ``` Description ----------- This class is immutable; all mutation operations return a new instance. Constructor ----------- | | | | | | --- | --- | --- | --- | | `constructor(options: HttpParamsOptions = {} as HttpParamsOptions)` Parameters | | | | | --- | --- | --- | | `options` | `[HttpParamsOptions](httpparamsoptions)` | Optional. Default is `{} as [HttpParamsOptions](httpparamsoptions)`. | | Methods ------- | has() | | --- | | Reports whether the body includes one or more values for a given parameter. | | `has(param: string): boolean` Parameters | | | | | --- | --- | --- | | `param` | `string` | The parameter name. | Returns `boolean`: True if the parameter has one or more values, false if it has no value or is not present. | | get() | | --- | | Retrieves the first value for a parameter. | | `get(param: string): string | null` Parameters | | | | | --- | --- | --- | | `param` | `string` | The parameter name. | Returns `string | null`: The first value of the given parameter, or `null` if the parameter is not present. | | getAll() | | --- | | Retrieves all values for a parameter. | | `getAll(param: string): string[] | null` Parameters | | | | | --- | --- | --- | | `param` | `string` | The parameter name. | Returns `string[] | null`: All values in a string array, or `null` if the parameter not present. | | keys() | | --- | | Retrieves all the parameters for this body. | | `keys(): string[]` Parameters There are no parameters. Returns `string[]`: The parameter names in a string array. | | append() | | --- | | Appends a new value to existing values for a parameter. | | `append(param: string, value: string | number | boolean): HttpParams` Parameters | | | | | --- | --- | --- | | `param` | `string` | The parameter name. | | `value` | `string | number | boolean` | The new value to add. | Returns `[HttpParams](httpparams)`: A new body with the appended value. | | appendAll() | | --- | | Constructs a new body with appended values for the given parameter name. | | `appendAll(params: { [param: string]: string | number | boolean | readonly (string | number | boolean)[]; }): HttpParams` Parameters | | | | | --- | --- | --- | | `params` | `object` | parameters and values | Returns `[HttpParams](httpparams)`: A new body with the new value. | | set() | | --- | | Replaces the value for a parameter. | | `set(param: string, value: string | number | boolean): HttpParams` Parameters | | | | | --- | --- | --- | | `param` | `string` | The parameter name. | | `value` | `string | number | boolean` | The new value. | Returns `[HttpParams](httpparams)`: A new body with the new value. | | delete() | | --- | | Removes a given value or all values from a parameter. | | `delete(param: string, value?: string | number | boolean): HttpParams` Parameters | | | | | --- | --- | --- | | `param` | `string` | The parameter name. | | `value` | `string | number | boolean` | The value to remove, if provided. Optional. Default is `undefined`. | Returns `[HttpParams](httpparams)`: A new body with the given value removed, or with all values removed if no value is specified. | | toString() | | --- | | Serializes the body to an encoded string, where key-value pairs (separated by `=`) are separated by `&`s. | | `toString(): string` Parameters There are no parameters. Returns `string` | angular HttpHandler HttpHandler =========== `class` Transforms an `[HttpRequest](httprequest)` into a stream of `[HttpEvent](httpevent)`s, one of which will likely be a `[HttpResponse](httpresponse)`. [See more...](httphandler#description) ``` abstract class HttpHandler { abstract handle(req: HttpRequest<any>): Observable<HttpEvent<any>> } ``` Subclasses ---------- * `[HttpBackend](httpbackend)` + `[JsonpClientBackend](jsonpclientbackend)` + `[HttpXhrBackend](httpxhrbackend)` Description ----------- `[HttpHandler](httphandler)` is injectable. When injected, the handler instance dispatches requests to the first interceptor in the chain, which dispatches to the second, etc, eventually reaching the `[HttpBackend](httpbackend)`. In an `[HttpInterceptor](httpinterceptor)`, the `[HttpHandler](httphandler)` parameter is the next interceptor in the chain. Methods ------- | handle() | | --- | | `abstract handle(req: HttpRequest<any>): Observable<HttpEvent<any>>` Parameters | | | | | --- | --- | --- | | `req` | `[HttpRequest](httprequest)<any>` | | Returns `Observable<[HttpEvent](httpevent)<any>>` | angular withNoXsrfProtection withNoXsrfProtection ==================== `function` Disables XSRF protection in the configuration of the current `[HttpClient](httpclient)` instance. [See more...](withnoxsrfprotection#description) ### `withNoXsrfProtection(): HttpFeature<HttpFeatureKind.NoXsrfProtection>` ###### Parameters There are no parameters. ###### Returns `[HttpFeature](httpfeature)<[HttpFeatureKind.NoXsrfProtection](httpfeaturekind#NoXsrfProtection)>` See also -------- * provideHttpClient Description ----------- This feature is incompatible with the `[withXsrfConfiguration](withxsrfconfiguration)` feature. angular HttpEventType HttpEventType ============= `enum` Type enumeration for the different kinds of `[HttpEvent](httpevent)`. ``` enum HttpEventType { Sent UploadProgress ResponseHeader DownloadProgress Response User } ``` Members ------- | Member | Description | | --- | --- | | `Sent` | The request was sent out over the wire. | | `UploadProgress` | An upload progress event was received. | | `ResponseHeader` | The response status code and headers were received. | | `DownloadProgress` | A download progress event was received. | | `Response` | The full response including the body was received. | | `User` | A custom event from an interceptor or a backend. | angular withJsonpSupport withJsonpSupport ================ `function` Add JSONP support to the configuration of the current `[HttpClient](httpclient)` instance. ### `withJsonpSupport(): HttpFeature<HttpFeatureKind.JsonpSupport>` ###### Parameters There are no parameters. ###### Returns `[HttpFeature](httpfeature)<[HttpFeatureKind.JsonpSupport](httpfeaturekind#JsonpSupport)>` See also -------- * provideHttpClient angular HttpUserEvent HttpUserEvent ============= `interface` A user-defined event. [See more...](httpuserevent#description) ``` interface HttpUserEvent<T> { type: HttpEventType.User } ``` Description ----------- Grouping all custom events under this type ensures they will be handled and forwarded by all implementations of interceptors. Properties ---------- | Property | Description | | --- | --- | | `type: [HttpEventType.User](httpeventtype#User)` | | angular HttpXsrfTokenExtractor HttpXsrfTokenExtractor ====================== `class` Retrieves the current XSRF token to use with the next outgoing request. ``` abstract class HttpXsrfTokenExtractor { abstract getToken(): string | null } ``` Provided in ----------- * [``` HttpClientXsrfModule ```](httpclientxsrfmodule) Methods ------- | getToken() | | --- | | Get the XSRF token to use with an outgoing request. | | `abstract getToken(): string | null` Parameters There are no parameters. Returns `string | null` | | Will be called for every request, so the token may change between requests. | angular HttpContext HttpContext =========== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Http context stores arbitrary user defined values and ensures type safety without actually knowing the types. It is backed by a `Map` and guarantees that keys do not clash. [See more...](httpcontext#description) ``` class HttpContext { set<T>(token: HttpContextToken<T>, value: T): HttpContext get<T>(token: HttpContextToken<T>): T delete(token: HttpContextToken<unknown>): HttpContext has(token: HttpContextToken<unknown>): boolean keys(): IterableIterator<HttpContextToken<unknown>> } ``` Description ----------- This context is mutable and is shared between cloned requests unless explicitly specified. Further information is available in the [Usage Notes...](httpcontext#usage-notes) Methods ------- | set() | | --- | | Store a value in the context. If a value is already present it will be overwritten. | | `set<T>(token: HttpContextToken<T>, value: T): HttpContext` Parameters | | | | | --- | --- | --- | | `token` | `[HttpContextToken<T>](httpcontexttoken)` | The reference to an instance of `[HttpContextToken](httpcontexttoken)`. | | `value` | `T` | The value to store. | Returns `[HttpContext](httpcontext)`: A reference to itself for easy chaining. | | get() | | --- | | Retrieve the value associated with the given token. | | `get<T>(token: HttpContextToken<T>): T` Parameters | | | | | --- | --- | --- | | `token` | `[HttpContextToken<T>](httpcontexttoken)` | The reference to an instance of `[HttpContextToken](httpcontexttoken)`. | Returns `T`: The stored value or default if one is defined. | | delete() | | --- | | Delete the value associated with the given token. | | `delete(token: HttpContextToken<unknown>): HttpContext` Parameters | | | | | --- | --- | --- | | `token` | `[HttpContextToken](httpcontexttoken)<unknown>` | The reference to an instance of `[HttpContextToken](httpcontexttoken)`. | Returns `[HttpContext](httpcontext)`: A reference to itself for easy chaining. | | has() | | --- | | Checks for existence of a given token. | | `has(token: HttpContextToken<unknown>): boolean` Parameters | | | | | --- | --- | --- | | `token` | `[HttpContextToken](httpcontexttoken)<unknown>` | The reference to an instance of `[HttpContextToken](httpcontexttoken)`. | Returns `boolean`: True if the token exists, false otherwise. | | keys() | | --- | | `keys(): IterableIterator<HttpContextToken<unknown>>` Parameters There are no parameters. Returns `IterableIterator<[HttpContextToken](httpcontexttoken)<unknown>>`: a list of tokens currently stored in the context. | Usage notes ----------- ### Usage Example ``` // inside cache.interceptors.ts export const IS_CACHE_ENABLED = new HttpContextToken<boolean>(() => false); export class CacheInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, delegate: HttpHandler): Observable<HttpEvent<any>> { if (req.context.get(IS_CACHE_ENABLED) === true) { return ...; } return delegate.handle(req); } } // inside a service this.httpClient.get('/api/weather', { context: new HttpContext().set(IS_CACHE_ENABLED, true) }).subscribe(...); ``` angular withXsrfConfiguration withXsrfConfiguration ===================== `function` Customizes the XSRF protection for the configuration of the current `[HttpClient](httpclient)` instance. [See more...](withxsrfconfiguration#description) ### `withXsrfConfiguration(__0: { cookieName?: string; headerName?: string; }): HttpFeature<HttpFeatureKind.CustomXsrfConfiguration>` ###### Parameters | | | | | --- | --- | --- | | `__0` | `object` | | ###### Returns `[HttpFeature](httpfeature)<[HttpFeatureKind.CustomXsrfConfiguration](httpfeaturekind#CustomXsrfConfiguration)>` See also -------- * provideHttpClient Description ----------- This feature is incompatible with the `[withNoXsrfProtection](withnoxsrfprotection)` feature. angular HttpParamsOptions HttpParamsOptions ================= `interface` Options used to construct an `[HttpParams](httpparams)` instance. ``` interface HttpParamsOptions { fromString?: string fromObject?: {...} encoder?: HttpParameterCodec } ``` Properties ---------- | Property | Description | | --- | --- | | `fromString?: string` | String representation of the HTTP parameters in URL-query-string format. Mutually exclusive with `fromObject`. | | `fromObject?: { [param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>; }` | Object map of the HTTP parameters. Mutually exclusive with `fromString`. | | `encoder?: [HttpParameterCodec](httpparametercodec)` | Encoding codec used to parse and serialize the parameters. |
programming_docs
angular HttpClientModule HttpClientModule ================ `ngmodule` Configures the [dependency injector](../../../guide/glossary#injector) for `[HttpClient](httpclient)` with supporting services for XSRF. Automatically imported by `[HttpClientModule](httpclientmodule)`. [See more...](httpclientmodule#description) ``` class HttpClientModule { } ``` Description ----------- You can add interceptors to the chain behind `[HttpClient](httpclient)` by binding them to the multiprovider for built-in [DI token](../../../guide/glossary#di-token) `[HTTP\_INTERCEPTORS](http_interceptors)`. Providers --------- | Provider | | --- | | ``` provideHttpClient(withInterceptorsFromDi()) ``` | angular HttpUrlEncodingCodec HttpUrlEncodingCodec ==================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Provides encoding and decoding of URL parameter and query-string values. [See more...](httpurlencodingcodec#description) ``` class HttpUrlEncodingCodec implements HttpParameterCodec { encodeKey(key: string): string encodeValue(value: string): string decodeKey(key: string): string decodeValue(value: string) } ``` Description ----------- Serializes and parses URL parameter keys and values to encode and decode them. If you pass URL query parameters without encoding, the query parameters can be misinterpreted at the receiving end. Methods ------- | encodeKey() | | --- | | Encodes a key name for a URL parameter or query-string. | | `encodeKey(key: string): string` Parameters | | | | | --- | --- | --- | | `key` | `string` | The key name. | Returns `string`: The encoded key name. | | encodeValue() | | --- | | Encodes the value of a URL parameter or query-string. | | `encodeValue(value: string): string` Parameters | | | | | --- | --- | --- | | `value` | `string` | The value. | Returns `string`: The encoded value. | | decodeKey() | | --- | | Decodes an encoded URL parameter or query-string key. | | `decodeKey(key: string): string` Parameters | | | | | --- | --- | --- | | `key` | `string` | The encoded key name. | Returns `string`: The decoded key name. | | decodeValue() | | --- | | Decodes an encoded URL parameter or query-string value. | | `decodeValue(value: string)` Parameters | | | | | --- | --- | --- | | `value` | `string` | The encoded value. | | angular HTTP_INTERCEPTORS HTTP\_INTERCEPTORS ================== `const` A multi-provider token that represents the array of registered `[HttpInterceptor](httpinterceptor)` objects. ### `const HTTP_INTERCEPTORS: InjectionToken<HttpInterceptor[]>;` angular withRequestsMadeViaParent withRequestsMadeViaParent ========================= `function` `[developer preview](../../../guide/releases#developer-preview)` Configures the current `[HttpClient](httpclient)` instance to make requests via the parent injector's `[HttpClient](httpclient)` instead of directly. [See more...](withrequestsmadeviaparent#description) ### `withRequestsMadeViaParent(): HttpFeature<HttpFeatureKind.RequestsMadeViaParent>` ###### Parameters There are no parameters. ###### Returns `[HttpFeature](httpfeature)<[HttpFeatureKind.RequestsMadeViaParent](httpfeaturekind#RequestsMadeViaParent)>` See also -------- * provideHttpClient Description ----------- By default, `[provideHttpClient](providehttpclient)` configures `[HttpClient](httpclient)` in its injector to be an independent instance. For example, even if `[HttpClient](httpclient)` is configured in the parent injector with one or more interceptors, they will not intercept requests made via this instance. With this option enabled, once the request has passed through the current injector's interceptors, it will be delegated to the parent injector's `[HttpClient](httpclient)` chain instead of dispatched directly, and interceptors in the parent configuration will be applied to the request. If there are several `[HttpClient](httpclient)` instances in the injector hierarchy, it's possible for `[withRequestsMadeViaParent](withrequestsmadeviaparent)` to be used at multiple levels, which will cause the request to "bubble up" until either reaching the root level or an `[HttpClient](httpclient)` which was not configured with this option. angular JsonpClientBackend JsonpClientBackend ================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Processes an `[HttpRequest](httprequest)` with the JSONP method, by performing JSONP style requests. ``` class JsonpClientBackend implements HttpBackend { handle(req: HttpRequest<never>): Observable<HttpEvent<any>> } ``` See also -------- * `[HttpHandler](httphandler)` * `[HttpXhrBackend](httpxhrbackend)` Methods ------- | handle() | | --- | | Processes a JSONP request and returns an event stream of the results. | | `handle(req: HttpRequest<never>): Observable<HttpEvent<any>>` Parameters | | | | | --- | --- | --- | | `req` | `[HttpRequest](httprequest)<never>` | The request object. | Returns `Observable<[HttpEvent](httpevent)<any>>`: An observable of the response events. | angular HttpClientJsonpModule HttpClientJsonpModule ===================== `ngmodule` Configures the [dependency injector](../../../guide/glossary#injector) for `[HttpClient](httpclient)` with supporting services for JSONP. Without this module, Jsonp requests reach the backend with method JSONP, where they are rejected. ``` class HttpClientJsonpModule { } ``` Providers --------- | Provider | | --- | | ``` withJsonpSupport().ɵproviders ``` | angular HttpHeaders HttpHeaders =========== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Represents the header configuration options for an HTTP request. Instances are immutable. Modifying methods return a cloned instance with the change. The original object is never changed. ``` class HttpHeaders { constructor(headers?: string | { [name: string]: string | string[]; }) has(name: string): boolean get(name: string): string | null keys(): string[] getAll(name: string): string[] | null append(name: string, value: string | string[]): HttpHeaders set(name: string, value: string | string[]): HttpHeaders delete(name: string, value?: string | string[]): HttpHeaders } ``` Constructor ----------- | | | --- | | Constructs a new HTTP header object with the given values. This class is "final" and should not be extended. See the [public API notes](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes). | | `constructor(headers?: string | { [name: string]: string | string[]; })` Parameters | | | | | --- | --- | --- | | `headers` | `string | { [name: string]: string | string[]; }` | Optional. Default is `undefined`. | | Methods ------- | has() | | --- | | Checks for existence of a given header. | | `has(name: string): boolean` Parameters | | | | | --- | --- | --- | | `name` | `string` | The header name to check for existence. | Returns `boolean`: True if the header exists, false otherwise. | | get() | | --- | | Retrieves the first value of a given header. | | `get(name: string): string | null` Parameters | | | | | --- | --- | --- | | `name` | `string` | The header name. | Returns `string | null`: The value string if the header exists, null otherwise | | keys() | | --- | | Retrieves the names of the headers. | | `keys(): string[]` Parameters There are no parameters. Returns `string[]`: A list of header names. | | getAll() | | --- | | Retrieves a list of values for a given header. | | `getAll(name: string): string[] | null` Parameters | | | | | --- | --- | --- | | `name` | `string` | The header name from which to retrieve values. | Returns `string[] | null`: A string of values if the header exists, null otherwise. | | append() | | --- | | Appends a new value to the existing set of values for a header and returns them in a clone of the original instance. | | `append(name: string, value: string | string[]): HttpHeaders` Parameters | | | | | --- | --- | --- | | `name` | `string` | The header name for which to append the values. | | `value` | `string | string[]` | The value to append. | Returns `[HttpHeaders](httpheaders)`: A clone of the HTTP headers object with the value appended to the given header. | | set() | | --- | | Sets or modifies a value for a given header in a clone of the original instance. If the header already exists, its value is replaced with the given value in the returned object. | | `set(name: string, value: string | string[]): HttpHeaders` Parameters | | | | | --- | --- | --- | | `name` | `string` | The header name. | | `value` | `string | string[]` | The value or values to set or override for the given header. | Returns `[HttpHeaders](httpheaders)`: A clone of the HTTP headers object with the newly set header value. | | delete() | | --- | | Deletes values for a given header in a clone of the original instance. | | `delete(name: string, value?: string | string[]): HttpHeaders` Parameters | | | | | --- | --- | --- | | `name` | `string` | The header name. | | `value` | `string | string[]` | The value or values to delete for the given header. Optional. Default is `undefined`. | Returns `[HttpHeaders](httpheaders)`: A clone of the HTTP headers object with the given value deleted. | angular HttpDownloadProgressEvent HttpDownloadProgressEvent ========================= `interface` A download progress event. ``` interface HttpDownloadProgressEvent extends HttpProgressEvent { type: HttpEventType.DownloadProgress partialText?: string // inherited from common/http/HttpProgressEvent type: HttpEventType.DownloadProgress | HttpEventType.UploadProgress loaded: number total?: number } ``` Properties ---------- | Property | Description | | --- | --- | | `type: [HttpEventType.DownloadProgress](httpeventtype#DownloadProgress)` | | | `partialText?: string` | The partial response body as downloaded so far. Only present if the responseType was `text`. | angular HttpResponseBase HttpResponseBase ================ `class` Base class for both `[HttpResponse](httpresponse)` and `[HttpHeaderResponse](httpheaderresponse)`. ``` abstract class HttpResponseBase { constructor(init: { headers?: HttpHeaders; status?: number; statusText?: string; url?: string; }, defaultStatus: number = HttpStatusCode.Ok, defaultStatusText: string = 'OK') headers: HttpHeaders status: number statusText: string url: string | null ok: boolean type: HttpEventType.Response | HttpEventType.ResponseHeader } ``` Subclasses ---------- * `[HttpErrorResponse](httperrorresponse)` * `[HttpHeaderResponse](httpheaderresponse)` * `[HttpResponse](httpresponse)` Constructor ----------- | | | --- | | Super-constructor for all responses. | | `constructor(init: { headers?: HttpHeaders; status?: number; statusText?: string; url?: string; }, defaultStatus: number = HttpStatusCode.Ok, defaultStatusText: string = 'OK')` Parameters | | | | | --- | --- | --- | | `init` | `object` | | | `defaultStatus` | `number` | Optional. Default is `[HttpStatusCode.Ok](httpstatuscode#Ok)`. | | `defaultStatusText` | `string` | Optional. Default is `'OK'`. | | | The single parameter accepted is an initialization hash. Any properties of the response passed there will override the default values. | Properties ---------- | Property | Description | | --- | --- | | `headers: [HttpHeaders](httpheaders)` | Read-Only All response headers. | | `status: number` | Read-Only Response status code. | | `statusText: string` | Read-Only Textual description of response status code, defaults to OK. Do not depend on this. | | `url: string | null` | Read-Only URL of the resource retrieved, or null if not available. | | `ok: boolean` | Read-Only Whether the status code falls in the 2xx range. | | `type: [HttpEventType.Response](httpeventtype#Response) | [HttpEventType.ResponseHeader](httpeventtype#ResponseHeader)` | Read-Only Type of the response, narrowed to either the full response or the header. | angular HttpStatusCode HttpStatusCode ============== `enum` Http status codes. As per <https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml> ``` enum HttpStatusCode { Continue: 100 SwitchingProtocols: 101 Processing: 102 EarlyHints: 103 Ok: 200 Created: 201 Accepted: 202 NonAuthoritativeInformation: 203 NoContent: 204 ResetContent: 205 PartialContent: 206 MultiStatus: 207 AlreadyReported: 208 ImUsed: 226 MultipleChoices: 300 MovedPermanently: 301 Found: 302 SeeOther: 303 NotModified: 304 UseProxy: 305 Unused: 306 TemporaryRedirect: 307 PermanentRedirect: 308 BadRequest: 400 Unauthorized: 401 PaymentRequired: 402 Forbidden: 403 NotFound: 404 MethodNotAllowed: 405 NotAcceptable: 406 ProxyAuthenticationRequired: 407 RequestTimeout: 408 Conflict: 409 Gone: 410 LengthRequired: 411 PreconditionFailed: 412 PayloadTooLarge: 413 UriTooLong: 414 UnsupportedMediaType: 415 RangeNotSatisfiable: 416 ExpectationFailed: 417 ImATeapot: 418 MisdirectedRequest: 421 UnprocessableEntity: 422 Locked: 423 FailedDependency: 424 TooEarly: 425 UpgradeRequired: 426 PreconditionRequired: 428 TooManyRequests: 429 RequestHeaderFieldsTooLarge: 431 UnavailableForLegalReasons: 451 InternalServerError: 500 NotImplemented: 501 BadGateway: 502 ServiceUnavailable: 503 GatewayTimeout: 504 HttpVersionNotSupported: 505 VariantAlsoNegotiates: 506 InsufficientStorage: 507 LoopDetected: 508 NotExtended: 510 NetworkAuthenticationRequired: 511 } ``` Members ------- | Member | Description | | --- | --- | | `Continue: 100` | | | `SwitchingProtocols: 101` | | | `Processing: 102` | | | `EarlyHints: 103` | | | `Ok: 200` | | | `Created: 201` | | | `Accepted: 202` | | | `NonAuthoritativeInformation: 203` | | | `NoContent: 204` | | | `ResetContent: 205` | | | `PartialContent: 206` | | | `MultiStatus: 207` | | | `AlreadyReported: 208` | | | `ImUsed: 226` | | | `MultipleChoices: 300` | | | `MovedPermanently: 301` | | | `Found: 302` | | | `SeeOther: 303` | | | `NotModified: 304` | | | `UseProxy: 305` | | | `Unused: 306` | | | `TemporaryRedirect: 307` | | | `PermanentRedirect: 308` | | | `BadRequest: 400` | | | `Unauthorized: 401` | | | `PaymentRequired: 402` | | | `Forbidden: 403` | | | `NotFound: 404` | | | `MethodNotAllowed: 405` | | | `NotAcceptable: 406` | | | `ProxyAuthenticationRequired: 407` | | | `RequestTimeout: 408` | | | `Conflict: 409` | | | `Gone: 410` | | | `LengthRequired: 411` | | | `PreconditionFailed: 412` | | | `PayloadTooLarge: 413` | | | `UriTooLong: 414` | | | `UnsupportedMediaType: 415` | | | `RangeNotSatisfiable: 416` | | | `ExpectationFailed: 417` | | | `ImATeapot: 418` | | | `MisdirectedRequest: 421` | | | `UnprocessableEntity: 422` | | | `Locked: 423` | | | `FailedDependency: 424` | | | `TooEarly: 425` | | | `UpgradeRequired: 426` | | | `PreconditionRequired: 428` | | | `TooManyRequests: 429` | | | `RequestHeaderFieldsTooLarge: 431` | | | `UnavailableForLegalReasons: 451` | | | `InternalServerError: 500` | | | `NotImplemented: 501` | | | `BadGateway: 502` | | | `ServiceUnavailable: 503` | | | `GatewayTimeout: 504` | | | `HttpVersionNotSupported: 505` | | | `VariantAlsoNegotiates: 506` | | | `InsufficientStorage: 507` | | | `LoopDetected: 508` | | | `NotExtended: 510` | | | `NetworkAuthenticationRequired: 511` | | angular HttpContextToken HttpContextToken ================ `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A token used to manipulate and access values stored in `[HttpContext](httpcontext)`. ``` class HttpContextToken<T> { constructor(defaultValue: () => T) defaultValue: () => T } ``` Constructor ----------- | | | | | | --- | --- | --- | --- | | `constructor(defaultValue: () => T)` Parameters | | | | | --- | --- | --- | | `defaultValue` | `() => T` | | | Properties ---------- | Property | Description | | --- | --- | | `defaultValue: () => T` | Read-Only Declared in Constructor | angular XhrFactory XhrFactory ========== `type-alias` `deprecated` A wrapper around the `XMLHttpRequest` constructor. **Deprecated:** `[XhrFactory](../xhrfactory)` has moved, please import `[XhrFactory](../xhrfactory)` from `@angular/common` instead. ``` type XhrFactory = XhrFactory_fromAngularCommon; ``` See also -------- * `[XhrFactory](../xhrfactory)` angular HttpHeaderResponse HttpHeaderResponse ================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A partial HTTP response which only includes the status and header data, but no response body. [See more...](httpheaderresponse#description) ``` class HttpHeaderResponse extends HttpResponseBase { constructor(init: { headers?: HttpHeaders; status?: number; statusText?: string; url?: string; } = {}) type: HttpEventType.ResponseHeader clone(update: { headers?: HttpHeaders; status?: number; statusText?: string; url?: string; } = {}): HttpHeaderResponse // inherited from common/http/HttpResponseBase constructor(init: { headers?: HttpHeaders; status?: number; statusText?: string; url?: string; }, defaultStatus: number = HttpStatusCode.Ok, defaultStatusText: string = 'OK') headers: HttpHeaders status: number statusText: string url: string | null ok: boolean type: HttpEventType.Response | HttpEventType.ResponseHeader } ``` Description ----------- `[HttpHeaderResponse](httpheaderresponse)` is a `[HttpEvent](httpevent)` available on the response event stream, only when progress events are requested. Constructor ----------- | | | --- | | Create a new `[HttpHeaderResponse](httpheaderresponse)` with the given parameters. This class is "final" and should not be extended. See the [public API notes](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes). | | `constructor(init: { headers?: HttpHeaders; status?: number; statusText?: string; url?: string; } = {})` Parameters | | | | | --- | --- | --- | | `init` | `object` | Optional. Default is `{}`. | | Properties ---------- | Property | Description | | --- | --- | | `type: [HttpEventType.ResponseHeader](httpeventtype#ResponseHeader)` | Read-Only | Methods ------- | clone() | | --- | | Copy this `[HttpHeaderResponse](httpheaderresponse)`, overriding its contents with the given parameter hash. | | `clone(update: { headers?: HttpHeaders; status?: number; statusText?: string; url?: string; } = {}): HttpHeaderResponse` Parameters | | | | | --- | --- | --- | | `update` | `object` | Optional. Default is `{}`. | Returns `[HttpHeaderResponse](httpheaderresponse)` | angular provideHttpClient provideHttpClient ================= `function` Configures Angular's `[HttpClient](httpclient)` service to be available for injection. [See more...](providehttpclient#description) ### `provideHttpClient(...features: HttpFeature<HttpFeatureKind>[]): EnvironmentProviders` ###### Parameters | | | | | --- | --- | --- | | `features` | `[HttpFeature](httpfeature)<[HttpFeatureKind](httpfeaturekind)>[]` | | ###### Returns `[EnvironmentProviders](../../core/environmentproviders)` See also -------- * withInterceptors * withInterceptorsFromDi * withXsrfConfiguration * withNoXsrfProtection * withJsonpSupport * withRequestsMadeViaParent Description ----------- By default, `[HttpClient](httpclient)` will be configured for injection with its default options for XSRF protection of outgoing requests. Additional configuration options can be provided by passing feature functions to `[provideHttpClient](providehttpclient)`. For example, HTTP interceptors can be added using the `[withInterceptors](withinterceptors)(...)` feature.
programming_docs
angular HttpClient HttpClient ========== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Performs HTTP requests. This service is available as an injectable class, with methods to perform HTTP requests. Each request method has multiple signatures, and the return type varies based on the signature that is called (mainly the values of `observe` and `responseType`). [See more...](httpclient#description) ``` class HttpClient { request(first: string | HttpRequest<any>, url?: string, options: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body" | "events" | "response"; params?: HttpParams | { ...; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any> delete(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body" | "events" | "response"; params?: HttpParams | { ...; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; body?: any; } = {}): Observable<any> get(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body" | "events" | "response"; params?: HttpParams | { ...; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any> head(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body" | "events" | "response"; params?: HttpParams | { ...; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any> jsonp<T>(url: string, callbackParam: string): Observable<T> options(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body" | "events" | "response"; params?: HttpParams | { ...; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any> patch(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body" | "events" | "response"; params?: HttpParams | { ...; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any> post(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body" | "events" | "response"; params?: HttpParams | { ...; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any> put(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body" | "events" | "response"; params?: HttpParams | { ...; }; reportProgress?: boolean; responseType?: "arraybuffer" | ... 2 more ... | "json"; withCredentials?: boolean; } = {}): Observable<any> } ``` See also -------- * [HTTP Guide](../../../guide/http) * [HTTP Request](httprequest) Description ----------- Note that the `responseType` *options* value is a String that identifies the single data type of the response. A single overload version of the method handles each response type. The value of `responseType` cannot be a union, as the combined signature could imply. Further information is available in the [Usage Notes...](httpclient#usage-notes) Methods ------- | request() | | --- | | Constructs an observable for a generic HTTP request that, when subscribed, fires the request through the chain of registered interceptors and on to the server. | | 17 overloads... Show All Hide All Overload #1 Sends an `[HttpRequest](httprequest)` and returns a stream of `[HttpEvent](httpevent)`s. `request<R>(req: HttpRequest<any>): Observable<HttpEvent<R>>` Parameters | | | | | --- | --- | --- | | `req` | `[HttpRequest](httprequest)<any>` | | Returns `Observable<[HttpEvent](httpevent)<R>>`: An `Observable` of the response, with the response body as a stream of `[HttpEvent](httpevent)`s. Overload #2 Constructs a request that interprets the body as an `ArrayBuffer` and returns the response in an `ArrayBuffer`. `request(method: string, url: string, options: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | ... 2 more ... | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boole...): Observable<ArrayBuffer>` Parameters | | | | | --- | --- | --- | | `method` | `string` | The HTTP method. | | `url` | `string` | The endpoint URL. | | `options` | `{ body?: any; headers?: [HttpHeaders](httpheaders) | { [header: string]: string | string[]; }; context?: [HttpContext](httpcontext); observe?: "body"; params?: [HttpParams](httpparams) | { [param: string]: string | ... 2 more ... | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boole...` | The HTTP options to send with the request. | Returns `Observable<ArrayBuffer>`: An `Observable` of the response, with the response body as an `ArrayBuffer`. Overload #3 Constructs a request that interprets the body as a blob and returns the response as a blob. `request(method: string, url: string, options: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | ... 2 more ... | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<Blob>` Parameters | | | | | --- | --- | --- | | `method` | `string` | The HTTP method. | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<Blob>`: An `Observable` of the response, with the response body of type `Blob`. Overload #4 Constructs a request that interprets the body as a text string and returns a string value. `request(method: string, url: string, options: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | ... 2 more ... | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<string>` Parameters | | | | | --- | --- | --- | | `method` | `string` | The HTTP method. | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<string>`: An `Observable` of the response, with the response body of type string. Overload #5 Constructs a request that interprets the body as an `ArrayBuffer` and returns the the full event stream. `request(method: string, url: string, options: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; observe: "events"; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: bo...): Observable<HttpEvent<ArrayBuffer>>` Parameters | | | | | --- | --- | --- | | `method` | `string` | The HTTP method. | | `url` | `string` | The endpoint URL. | | `options` | `{ body?: any; headers?: [HttpHeaders](httpheaders) | { [header: string]: string | string[]; }; context?: [HttpContext](httpcontext); params?: [HttpParams](httpparams) | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; observe: "events"; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: bo...` | The HTTP options to send with the request. | Returns `Observable<[HttpEvent](httpevent)<ArrayBuffer>>`: An `Observable` of the response, with the response body as an array of `[HttpEvent](httpevent)`s for the request. Overload #6 Constructs a request that interprets the body as a `Blob` and returns the full event stream. `request(method: string, url: string, options: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | ... 2 more ... | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<HttpEvent<Blob>>` Parameters | | | | | --- | --- | --- | | `method` | `string` | The HTTP method. | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpEvent](httpevent)<Blob>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with the response body of type `Blob`. Overload #7 Constructs a request which interprets the body as a text string and returns the full event stream. `request(method: string, url: string, options: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | ... 2 more ... | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<HttpEvent<string>>` Parameters | | | | | --- | --- | --- | | `method` | `string` | The HTTP method. | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpEvent](httpevent)<string>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with the response body of type string. Overload #8 Constructs a request which interprets the body as a JavaScript object and returns the full event stream. `request(method: string, url: string, options: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; reportProgress?: boolean; observe: "events"; params?: HttpParams | { ...; }; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpEvent<any>>` Parameters | | | | | --- | --- | --- | | `method` | `string` | The HTTP method. | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpEvent](httpevent)<any>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with the response body of type `Object`. Overload #9 Constructs a request which interprets the body as a JavaScript object and returns the full event stream. `request<R>(method: string, url: string, options: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; reportProgress?: boolean; observe: "events"; params?: HttpParams | { ...; }; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpEvent<R>>` Parameters | | | | | --- | --- | --- | | `method` | `string` | The HTTP method. | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpEvent](httpevent)<R>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with the response body of type `R`. Overload #10 Constructs a request which interprets the body as an `ArrayBuffer` and returns the full `[HttpResponse](httpresponse)`. `request(method: string, url: string, options: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { ...; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; }): Observable<HttpResponse<ArrayBuffer>>` Parameters | | | | | --- | --- | --- | | `method` | `string` | The HTTP method. | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpResponse](httpresponse)<ArrayBuffer>>`: An `Observable` of the `[HttpResponse](httpresponse)`, with the response body as an `ArrayBuffer`. Overload #11 Constructs a request which interprets the body as a `Blob` and returns the full `[HttpResponse](httpresponse)`. `request(method: string, url: string, options: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { ...; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<HttpResponse<Blob>>` Parameters | | | | | --- | --- | --- | | `method` | `string` | The HTTP method. | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpResponse](httpresponse)<Blob>>`: An `Observable` of the `[HttpResponse](httpresponse)`, with the response body of type `Blob`. Overload #12 Constructs a request which interprets the body as a text stream and returns the full `[HttpResponse](httpresponse)`. `request(method: string, url: string, options: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { ...; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<HttpResponse<string>>` Parameters | | | | | --- | --- | --- | | `method` | `string` | The HTTP method. | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpResponse](httpresponse)<string>>`: An `Observable` of the HTTP response, with the response body of type string. Overload #13 Constructs a request which interprets the body as a JavaScript object and returns the full `[HttpResponse](httpresponse)`. `request(method: string, url: string, options: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; reportProgress?: boolean; observe: "response"; params?: HttpParams | { ...; }; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpResponse<Object>>` Parameters | | | | | --- | --- | --- | | `method` | `string` | The HTTP method. | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpResponse](httpresponse)<Object>>`: An `Observable` of the full `[HttpResponse](httpresponse)`, with the response body of type `Object`. Overload #14 Constructs a request which interprets the body as a JavaScript object and returns the full `[HttpResponse](httpresponse)` with the response body in the requested type. `request<R>(method: string, url: string, options: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; reportProgress?: boolean; observe: "response"; params?: HttpParams | { ...; }; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpResponse<R>>` Parameters | | | | | --- | --- | --- | | `method` | `string` | The HTTP method. | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpResponse](httpresponse)<R>>`: An `Observable` of the full `[HttpResponse](httpresponse)`, with the response body of type `R`. Overload #15 Constructs a request which interprets the body as a JavaScript object and returns the full `[HttpResponse](httpresponse)` as a JavaScript object. `request(method: string, url: string, options?: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | ... 2 more ... | readonly (string | ... 1 more ... | boolean)[]; }; responseType?: "json"; reportProgress?: boolean; withCredentials?: boolean; }): Observable<Object>` Parameters | | | | | --- | --- | --- | | `method` | `string` | The HTTP method. | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. Optional. Default is `undefined`. | Returns `Observable<Object>`: An `Observable` of the `[HttpResponse](httpresponse)`, with the response body of type `Object`. Overload #16 Constructs a request which interprets the body as a JavaScript object with the response body of the requested type. `request<R>(method: string, url: string, options?: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | ... 2 more ... | readonly (string | ... 1 more ... | boolean)[]; }; responseType?: "json"; reportProgress?: boolean; withCredentials?: boolean; }): Observable<R>` Parameters | | | | | --- | --- | --- | | `method` | `string` | The HTTP method. | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. Optional. Default is `undefined`. | Returns `Observable<R>`: An `Observable` of the `[HttpResponse](httpresponse)`, with the response body of type `R`. Overload #17 Constructs a request where response type and requested observable are not known statically. `request(method: string, url: string, options?: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; observe?: "body" | ... 1 more ... | "response"; reportProgress?: boolean; responseType?: "arra...): Observable<any>` Parameters | | | | | --- | --- | --- | | `method` | `string` | The HTTP method. | | `url` | `string` | The endpoint URL. | | `options` | `{ body?: any; headers?: [HttpHeaders](httpheaders) | { [header: string]: string | string[]; }; context?: [HttpContext](httpcontext); params?: [HttpParams](httpparams) | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; observe?: "body" | ... 1 more ... | "response"; reportProgress?: boolean; responseType?: "arra...` | The HTTP options to send with the request. Optional. Default is `undefined`. | Returns `Observable<any>`: An `Observable` of the requested response, with body of type `any`. | | You can pass an `[HttpRequest](httprequest)` directly as the only parameter. In this case, the call returns an observable of the raw `[HttpEvent](httpevent)` stream. Alternatively you can pass an HTTP method as the first parameter, a URL string as the second, and an options hash containing the request body as the third. See `addBody()`. In this case, the specified `responseType` and `observe` options determine the type of returned observable.* The `responseType` value determines how a successful response body is parsed. * If `responseType` is the default `json`, you can pass a type interface for the resulting object as a type parameter to the call. The `observe` value determines the return type, according to what you are interested in observing.* An `observe` value of events returns an observable of the raw `[HttpEvent](httpevent)` stream, including progress events by default. * An `observe` value of response returns an observable of `[HttpResponse<T>](httpresponse)`, where the `T` parameter depends on the `responseType` and any optionally provided type parameter. * An `observe` value of body returns an observable of `<T>` with the same `T` body type. | | delete() | | --- | | Constructs an observable that, when subscribed, causes the configured `DELETE` request to execute on the server. See the individual overloads for details on the return type. | | 15 overloads... Show All Hide All Overload #1 Constructs a `DELETE` request that interprets the body as an `ArrayBuffer` and returns the response as an `ArrayBuffer`. `delete(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; body?:...): Observable<ArrayBuffer>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `{ headers?: [HttpHeaders](httpheaders) | { [header: string]: string | string[]; }; context?: [HttpContext](httpcontext); observe?: "body"; params?: [HttpParams](httpparams) | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; body?:...` | The HTTP options to send with the request. | Returns `Observable<ArrayBuffer>`: An `Observable` of the response body as an `ArrayBuffer`. Overload #2 Constructs a `DELETE` request that interprets the body as a `Blob` and returns the response as a `Blob`. `delete(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; body?: any; }): Observable<Blob>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<Blob>`: An `Observable` of the response body as a `Blob`. Overload #3 Constructs a `DELETE` request that interprets the body as a text string and returns a string. `delete(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; body?: any; }): Observable<string>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<string>`: An `Observable` of the response, with the response body of type string. Overload #4 Constructs a `DELETE` request that interprets the body as an `ArrayBuffer` and returns the full event stream. `delete(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; body?...): Observable<HttpEvent<ArrayBuffer>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `{ headers?: [HttpHeaders](httpheaders) | { [header: string]: string | string[]; }; observe: "events"; context?: [HttpContext](httpcontext); params?: [HttpParams](httpparams) | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; body?...` | The HTTP options to send with the request. | Returns `Observable<[HttpEvent](httpevent)<ArrayBuffer>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with response body as an `ArrayBuffer`. Overload #5 Constructs a `DELETE` request that interprets the body as a `Blob` and returns the full event stream. `delete(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; body?: any; }): Observable<HttpEvent<Blob>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpEvent](httpevent)<Blob>>`: An `Observable` of all the `[HttpEvent](httpevent)`s for the request, with the response body as a `Blob`. Overload #6 Constructs a `DELETE` request that interprets the body as a text string and returns the full event stream. `delete(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; body?: any; }): Observable<HttpEvent<string>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpEvent](httpevent)<string>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with the response body of type string. Overload #7 Constructs a `DELETE` request that interprets the body as JSON and returns the full event stream. `delete(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; body?: any; }): Observable<HttpEvent<Object>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpEvent](httpevent)<Object>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with response body of type `Object`. Overload #8 Constructs a `DELETE`request that interprets the body as JSON and returns the full event stream. `delete<T>(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; body?: any; }): Observable<HttpEvent<T>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpEvent](httpevent)<T>>`: An `Observable` of all the `[HttpEvent](httpevent)`s for the request, with a response body in the requested type. Overload #9 Constructs a `DELETE` request that interprets the body as an `ArrayBuffer` and returns the full `[HttpResponse](httpresponse)`. `delete(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; bod...): Observable<HttpResponse<ArrayBuffer>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `{ headers?: [HttpHeaders](httpheaders) | { [header: string]: string | string[]; }; observe: "response"; context?: [HttpContext](httpcontext); params?: [HttpParams](httpparams) | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; bod...` | The HTTP options to send with the request. | Returns `Observable<[HttpResponse](httpresponse)<ArrayBuffer>>`: An `Observable` of the full `[HttpResponse](httpresponse)`, with the response body as an `ArrayBuffer`. Overload #10 Constructs a `DELETE` request that interprets the body as a `Blob` and returns the full `[HttpResponse](httpresponse)`. `delete(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; body?: any...): Observable<HttpResponse<Blob>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `{ headers?: [HttpHeaders](httpheaders) | { [header: string]: string | string[]; }; observe: "response"; context?: [HttpContext](httpcontext); params?: [HttpParams](httpparams) | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; body?: any...` | The HTTP options to send with the request. | Returns `Observable<[HttpResponse](httpresponse)<Blob>>`: An `Observable` of the `[HttpResponse](httpresponse)`, with the response body of type `Blob`. Overload #11 Constructs a `DELETE` request that interprets the body as a text stream and returns the full `[HttpResponse](httpresponse)`. `delete(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; body?: any...): Observable<HttpResponse<string>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `{ headers?: [HttpHeaders](httpheaders) | { [header: string]: string | string[]; }; observe: "response"; context?: [HttpContext](httpcontext); params?: [HttpParams](httpparams) | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; body?: any...` | The HTTP options to send with the request. | Returns `Observable<[HttpResponse](httpresponse)<string>>`: An `Observable` of the full `[HttpResponse](httpresponse)`, with the response body of type string. Overload #12 Constructs a `DELETE` request the interprets the body as a JavaScript object and returns the full `[HttpResponse](httpresponse)`. `delete(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; body?: an...): Observable<HttpResponse<Object>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `{ headers?: [HttpHeaders](httpheaders) | { [header: string]: string | string[]; }; observe: "response"; context?: [HttpContext](httpcontext); params?: [HttpParams](httpparams) | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; body?: an...` | The HTTP options to send with the request. | Returns `Observable<[HttpResponse](httpresponse)<Object>>`: An `Observable` of the `[HttpResponse](httpresponse)`, with the response body of type `Object`. Overload #13 Constructs a `DELETE` request that interprets the body as JSON and returns the full `[HttpResponse](httpresponse)`. `delete<T>(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; body?: an...): Observable<HttpResponse<T>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `{ headers?: [HttpHeaders](httpheaders) | { [header: string]: string | string[]; }; observe: "response"; context?: [HttpContext](httpcontext); params?: [HttpParams](httpparams) | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; body?: an...` | The HTTP options to send with the request. | Returns `Observable<[HttpResponse](httpresponse)<T>>`: An `Observable` of the `[HttpResponse](httpresponse)`, with the response body of the requested type. Overload #14 Constructs a `DELETE` request that interprets the body as JSON and returns the response body as an object parsed from JSON. `delete(url: string, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; body?: any; }): Observable<Object>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. Optional. Default is `undefined`. | Returns `Observable<Object>`: An `Observable` of the response, with the response body of type `Object`. Overload #15 Constructs a DELETE request that interprets the body as JSON and returns the response in a given type. `delete<T>(url: string, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; body?: any; }): Observable<T>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. Optional. Default is `undefined`. | Returns `Observable<T>`: An `Observable` of the `[HttpResponse](httpresponse)`, with response body in the requested type. | | get() | | --- | | Constructs an observable that, when subscribed, causes the configured `GET` request to execute on the server. See the individual overloads for details on the return type. | | 15 overloads... Show All Hide All Overload #1 Constructs a `GET` request that interprets the body as an `ArrayBuffer` and returns the response in an `ArrayBuffer`. `get(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; }): Observable<ArrayBuffer>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<ArrayBuffer>`: An `Observable` of the response, with the response body as an `ArrayBuffer`. Overload #2 Constructs a `GET` request that interprets the body as a `Blob` and returns the response as a `Blob`. `get(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<Blob>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<Blob>`: An `Observable` of the response, with the response body as a `Blob`. Overload #3 Constructs a `GET` request that interprets the body as a text string and returns the response as a string value. `get(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<string>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<string>`: An `Observable` of the response, with the response body of type string. Overload #4 Constructs a `GET` request that interprets the body as an `ArrayBuffer` and returns the full event stream. `get(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; }): Observable<HttpEvent<ArrayBuffer>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpEvent](httpevent)<ArrayBuffer>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with the response body as an `ArrayBuffer`. Overload #5 Constructs a `GET` request that interprets the body as a `Blob` and returns the full event stream. `get(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<HttpEvent<Blob>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpEvent](httpevent)<Blob>>`: An `Observable` of the response, with the response body as a `Blob`. Overload #6 Constructs a `GET` request that interprets the body as a text string and returns the full event stream. `get(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<HttpEvent<string>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpEvent](httpevent)<string>>`: An `Observable` of the response, with the response body of type string. Overload #7 Constructs a `GET` request that interprets the body as JSON and returns the full event stream. `get(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpEvent<Object>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpEvent](httpevent)<Object>>`: An `Observable` of the response, with the response body of type `Object`. Overload #8 Constructs a `GET` request that interprets the body as JSON and returns the full event stream. `get<T>(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpEvent<T>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpEvent](httpevent)<T>>`: An `Observable` of the response, with a response body in the requested type. Overload #9 Constructs a `GET` request that interprets the body as an `ArrayBuffer` and returns the full `[HttpResponse](httpresponse)`. `get(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; }): Observable<HttpResponse<ArrayBuffer>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpResponse](httpresponse)<ArrayBuffer>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with the response body as an `ArrayBuffer`. Overload #10 Constructs a `GET` request that interprets the body as a `Blob` and returns the full `[HttpResponse](httpresponse)`. `get(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<HttpResponse<Blob>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpResponse](httpresponse)<Blob>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with the response body as a `Blob`. Overload #11 Constructs a `GET` request that interprets the body as a text stream and returns the full `[HttpResponse](httpresponse)`. `get(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<HttpResponse<string>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpResponse](httpresponse)<string>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with the response body of type string. Overload #12 Constructs a `GET` request that interprets the body as JSON and returns the full `[HttpResponse](httpresponse)`. `get(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpResponse<Object>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpResponse](httpresponse)<Object>>`: An `Observable` of the full `[HttpResponse](httpresponse)`, with the response body of type `Object`. Overload #13 Constructs a `GET` request that interprets the body as JSON and returns the full `[HttpResponse](httpresponse)`. `get<T>(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpResponse<T>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpResponse](httpresponse)<T>>`: An `Observable` of the full `[HttpResponse](httpresponse)` for the request, with a response body in the requested type. Overload #14 Constructs a `GET` request that interprets the body as JSON and returns the response body as an object parsed from JSON. `get(url: string, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<Object>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. Optional. Default is `undefined`. | Returns `Observable<Object>`: An `Observable` of the response body as a JavaScript object. Overload #15 Constructs a `GET` request that interprets the body as JSON and returns the response body in a given type. `get<T>(url: string, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<T>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. Optional. Default is `undefined`. | Returns `Observable<T>`: An `Observable` of the `[HttpResponse](httpresponse)`, with a response body in the requested type. | | head() | | --- | | Constructs an observable that, when subscribed, causes the configured `HEAD` request to execute on the server. The `HEAD` method returns meta information about the resource without transferring the resource itself. See the individual overloads for details on the return type. | | 15 overloads... Show All Hide All Overload #1 Constructs a `HEAD` request that interprets the body as an `ArrayBuffer` and returns the response as an `ArrayBuffer`. `head(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; }): Observable<ArrayBuffer>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<ArrayBuffer>`: An `Observable` of the response, with the response body as an `ArrayBuffer`. Overload #2 Constructs a `HEAD` request that interprets the body as a `Blob` and returns the response as a `Blob`. `head(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<Blob>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<Blob>`: An `Observable` of the response, with the response body as a `Blob`. Overload #3 Constructs a `HEAD` request that interprets the body as a text string and returns the response as a string value. `head(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<string>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<string>`: An `Observable` of the response, with the response body of type string. Overload #4 Constructs a `HEAD` request that interprets the body as an `ArrayBuffer` and returns the full event stream. `head(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; }): Observable<HttpEvent<ArrayBuffer>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpEvent](httpevent)<ArrayBuffer>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with the response body as an `ArrayBuffer`. Overload #5 Constructs a `HEAD` request that interprets the body as a `Blob` and returns the full event stream. `head(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<HttpEvent<Blob>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpEvent](httpevent)<Blob>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with the response body as a `Blob`. Overload #6 Constructs a `HEAD` request that interprets the body as a text string and returns the full event stream. `head(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<HttpEvent<string>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpEvent](httpevent)<string>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with the response body of type string. Overload #7 Constructs a `HEAD` request that interprets the body as JSON and returns the full HTTP event stream. `head(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpEvent<Object>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpEvent](httpevent)<Object>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with a response body of type `Object`. Overload #8 Constructs a `HEAD` request that interprets the body as JSON and returns the full event stream. `head<T>(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpEvent<T>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpEvent](httpevent)<T>>`: An `Observable` of all the `[HttpEvent](httpevent)`s for the request, with a response body in the requested type. Overload #9 Constructs a `HEAD` request that interprets the body as an `ArrayBuffer` and returns the full HTTP response. `head(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; }): Observable<HttpResponse<ArrayBuffer>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpResponse](httpresponse)<ArrayBuffer>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with the response body as an `ArrayBuffer`. Overload #10 Constructs a `HEAD` request that interprets the body as a `Blob` and returns the full `[HttpResponse](httpresponse)`. `head(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<HttpResponse<Blob>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpResponse](httpresponse)<Blob>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with the response body as a blob. Overload #11 Constructs a `HEAD` request that interprets the body as text stream and returns the full `[HttpResponse](httpresponse)`. `head(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<HttpResponse<string>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpResponse](httpresponse)<string>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with the response body of type string. Overload #12 Constructs a `HEAD` request that interprets the body as JSON and returns the full `[HttpResponse](httpresponse)`. `head(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpResponse<Object>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpResponse](httpresponse)<Object>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with the response body of type `Object`. Overload #13 Constructs a `HEAD` request that interprets the body as JSON and returns the full `[HttpResponse](httpresponse)`. `head<T>(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpResponse<T>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. | Returns `Observable<[HttpResponse](httpresponse)<T>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with a response body of the requested type. Overload #14 Constructs a `HEAD` request that interprets the body as JSON and returns the response body as an object parsed from JSON. `head(url: string, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<Object>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. Optional. Default is `undefined`. | Returns `Observable<Object>`: An `Observable` of the response, with the response body as an object parsed from JSON. Overload #15 Constructs a `HEAD` request that interprets the body as JSON and returns the response in a given type. `head<T>(url: string, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<T>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | The HTTP options to send with the request. Optional. Default is `undefined`. | Returns `Observable<T>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with a response body of the given type. | | jsonp() | | --- | | Constructs an `Observable` that, when subscribed, causes a request with the special method `JSONP` to be dispatched via the interceptor pipeline. The [JSONP pattern](https://en.wikipedia.org/wiki/JSONP) works around limitations of certain API endpoints that don't support newer, and preferable [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) protocol. JSONP treats the endpoint API as a JavaScript file and tricks the browser to process the requests even if the API endpoint is not located on the same domain (origin) as the client-side application making the request. The endpoint API must support JSONP callback for JSONP requests to work. The resource API returns the JSON response wrapped in a callback function. You can pass the callback function name as one of the query parameters. Note that JSONP requests can only be used with `GET` requests. | | Constructs a `JSONP` request for the given URL and name of the callback parameter. `jsonp(url: string, callbackParam: string): Observable<Object>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The resource URL. | | `callbackParam` | `string` | The callback function name. | Returns `Observable<Object>`: An `Observable` of the response object, with response body as an object. | | Constructs a `JSONP` request for the given URL and name of the callback parameter. `jsonp<T>(url: string, callbackParam: string): Observable<T>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The resource URL. | | `callbackParam` | `string` | The callback function name. You must install a suitable interceptor, such as one provided by `[HttpClientJsonpModule](httpclientjsonpmodule)`. If no such interceptor is reached, then the `JSONP` request can be rejected by the configured backend. | Returns `Observable<T>`: An `Observable` of the response object, with response body in the requested type. | | options() | | --- | | Constructs an `Observable` that, when subscribed, causes the configured `OPTIONS` request to execute on the server. This method allows the client to determine the supported HTTP methods and other capabilities of an endpoint, without implying a resource action. See the individual overloads for details on the return type. | | 15 overloads... Show All Hide All Overload #1 Constructs an `OPTIONS` request that interprets the body as an `ArrayBuffer` and returns the response as an `ArrayBuffer`. `options(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; }): Observable<ArrayBuffer>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | HTTP options. | Returns `Observable<ArrayBuffer>`: An `Observable` of the response, with the response body as an `ArrayBuffer`. Overload #2 Constructs an `OPTIONS` request that interprets the body as a `Blob` and returns the response as a `Blob`. `options(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<Blob>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | HTTP options. | Returns `Observable<Blob>`: An `Observable` of the response, with the response body as a `Blob`. Overload #3 Constructs an `OPTIONS` request that interprets the body as a text string and returns a string value. `options(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<string>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | HTTP options. | Returns `Observable<string>`: An `Observable` of the response, with the response body of type string. Overload #4 Constructs an `OPTIONS` request that interprets the body as an `ArrayBuffer` and returns the full event stream. `options(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; }): Observable<HttpEvent<ArrayBuffer>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | HTTP options. | Returns `Observable<[HttpEvent](httpevent)<ArrayBuffer>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with the response body as an `ArrayBuffer`. Overload #5 Constructs an `OPTIONS` request that interprets the body as a `Blob` and returns the full event stream. `options(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<HttpEvent<Blob>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | HTTP options. | Returns `Observable<[HttpEvent](httpevent)<Blob>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with the response body as a `Blob`. Overload #6 Constructs an `OPTIONS` request that interprets the body as a text string and returns the full event stream. `options(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<HttpEvent<string>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | HTTP options. | Returns `Observable<[HttpEvent](httpevent)<string>>`: An `Observable` of all the `[HttpEvent](httpevent)`s for the request, with the response body of type string. Overload #7 Constructs an `OPTIONS` request that interprets the body as JSON and returns the full event stream. `options(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpEvent<Object>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | HTTP options. | Returns `Observable<[HttpEvent](httpevent)<Object>>`: An `Observable` of all the `[HttpEvent](httpevent)`s for the request with the response body of type `Object`. Overload #8 Constructs an `OPTIONS` request that interprets the body as JSON and returns the full event stream. `options<T>(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpEvent<T>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | HTTP options. | Returns `Observable<[HttpEvent](httpevent)<T>>`: An `Observable` of all the `[HttpEvent](httpevent)`s for the request, with a response body in the requested type. Overload #9 Constructs an `OPTIONS` request that interprets the body as an `ArrayBuffer` and returns the full HTTP response. `options(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; }): Observable<HttpResponse<ArrayBuffer>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | HTTP options. | Returns `Observable<[HttpResponse](httpresponse)<ArrayBuffer>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with the response body as an `ArrayBuffer`. Overload #10 Constructs an `OPTIONS` request that interprets the body as a `Blob` and returns the full `[HttpResponse](httpresponse)`. `options(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<HttpResponse<Blob>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | HTTP options. | Returns `Observable<[HttpResponse](httpresponse)<Blob>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with the response body as a `Blob`. Overload #11 Constructs an `OPTIONS` request that interprets the body as text stream and returns the full `[HttpResponse](httpresponse)`. `options(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<HttpResponse<string>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | HTTP options. | Returns `Observable<[HttpResponse](httpresponse)<string>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with the response body of type string. Overload #12 Constructs an `OPTIONS` request that interprets the body as JSON and returns the full `[HttpResponse](httpresponse)`. `options(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpResponse<Object>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | HTTP options. | Returns `Observable<[HttpResponse](httpresponse)<Object>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with the response body of type `Object`. Overload #13 Constructs an `OPTIONS` request that interprets the body as JSON and returns the full `[HttpResponse](httpresponse)`. `options<T>(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpResponse<T>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | HTTP options. | Returns `Observable<[HttpResponse](httpresponse)<T>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with a response body in the requested type. Overload #14 Constructs an `OPTIONS` request that interprets the body as JSON and returns the response body as an object parsed from JSON. `options(url: string, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<Object>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | HTTP options. Optional. Default is `undefined`. | Returns `Observable<Object>`: An `Observable` of the response, with the response body as an object parsed from JSON. Overload #15 Constructs an `OPTIONS` request that interprets the body as JSON and returns the response in a given type. `options<T>(url: string, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<T>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `options` | `object` | HTTP options. Optional. Default is `undefined`. | Returns `Observable<T>`: An `Observable` of the `[HttpResponse](httpresponse)`, with a response body of the given type. | | patch() | | --- | | Constructs an observable that, when subscribed, causes the configured `PATCH` request to execute on the server. See the individual overloads for details on the return type. | | 15 overloads... Show All Hide All Overload #1 Constructs a `PATCH` request that interprets the body as an `ArrayBuffer` and returns the response as an `ArrayBuffer`. `patch(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; }): Observable<ArrayBuffer>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to edit. | | `options` | `object` | HTTP options. | Returns `Observable<ArrayBuffer>`: An `Observable` of the response, with the response body as an `ArrayBuffer`. Overload #2 Constructs a `PATCH` request that interprets the body as a `Blob` and returns the response as a `Blob`. `patch(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<Blob>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to edit. | | `options` | `object` | HTTP options. | Returns `Observable<Blob>`: An `Observable` of the response, with the response body as a `Blob`. Overload #3 Constructs a `PATCH` request that interprets the body as a text string and returns the response as a string value. `patch(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<string>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to edit. | | `options` | `object` | HTTP options. | Returns `Observable<string>`: An `Observable` of the response, with a response body of type string. Overload #4 Constructs a `PATCH` request that interprets the body as an `ArrayBuffer` and returns the full event stream. `patch(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; }): Observable<HttpEvent<ArrayBuffer>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to edit. | | `options` | `object` | HTTP options. | Returns `Observable<[HttpEvent](httpevent)<ArrayBuffer>>`: An `Observable` of all the `[HttpEvent](httpevent)`s for the request, with the response body as an `ArrayBuffer`. Overload #5 Constructs a `PATCH` request that interprets the body as a `Blob` and returns the full event stream. `patch(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<HttpEvent<Blob>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to edit. | | `options` | `object` | HTTP options. | Returns `Observable<[HttpEvent](httpevent)<Blob>>`: An `Observable` of all the `[HttpEvent](httpevent)`s for the request, with the response body as `Blob`. Overload #6 Constructs a `PATCH` request that interprets the body as a text string and returns the full event stream. `patch(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<HttpEvent<string>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to edit. | | `options` | `object` | HTTP options. | Returns `Observable<[HttpEvent](httpevent)<string>>`: An `Observable` of all the `[HttpEvent](httpevent)`s for the request, with a response body of type string. Overload #7 Constructs a `PATCH` request that interprets the body as JSON and returns the full event stream. `patch(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpEvent<Object>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to edit. | | `options` | `object` | HTTP options. | Returns `Observable<[HttpEvent](httpevent)<Object>>`: An `Observable` of all the `[HttpEvent](httpevent)`s for the request, with a response body of type `Object`. Overload #8 Constructs a `PATCH` request that interprets the body as JSON and returns the full event stream. `patch<T>(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpEvent<T>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to edit. | | `options` | `object` | HTTP options. | Returns `Observable<[HttpEvent](httpevent)<T>>`: An `Observable` of all the `[HttpEvent](httpevent)`s for the request, with a response body in the requested type. Overload #9 Constructs a `PATCH` request that interprets the body as an `ArrayBuffer` and returns the full `[HttpResponse](httpresponse)`. `patch(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; }): Observable<HttpResponse<ArrayBuffer>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to edit. | | `options` | `object` | HTTP options. | Returns `Observable<[HttpResponse](httpresponse)<ArrayBuffer>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with the response body as an `ArrayBuffer`. Overload #10 Constructs a `PATCH` request that interprets the body as a `Blob` and returns the full `[HttpResponse](httpresponse)`. `patch(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<HttpResponse<Blob>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to edit. | | `options` | `object` | HTTP options. | Returns `Observable<[HttpResponse](httpresponse)<Blob>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with the response body as a `Blob`. Overload #11 Constructs a `PATCH` request that interprets the body as a text stream and returns the full `[HttpResponse](httpresponse)`. `patch(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<HttpResponse<string>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to edit. | | `options` | `object` | HTTP options. | Returns `Observable<[HttpResponse](httpresponse)<string>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with a response body of type string. Overload #12 Constructs a `PATCH` request that interprets the body as JSON and returns the full `[HttpResponse](httpresponse)`. `patch(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpResponse<Object>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to edit. | | `options` | `object` | HTTP options. | Returns `Observable<[HttpResponse](httpresponse)<Object>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with a response body in the requested type. Overload #13 Constructs a `PATCH` request that interprets the body as JSON and returns the full `[HttpResponse](httpresponse)`. `patch<T>(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpResponse<T>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to edit. | | `options` | `object` | HTTP options. | Returns `Observable<[HttpResponse](httpresponse)<T>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with a response body in the given type. Overload #14 Constructs a `PATCH` request that interprets the body as JSON and returns the response body as an object parsed from JSON. `patch(url: string, body: any, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<Object>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to edit. | | `options` | `object` | HTTP options. Optional. Default is `undefined`. | Returns `Observable<Object>`: An `Observable` of the response, with the response body as an object parsed from JSON. Overload #15 Constructs a `PATCH` request that interprets the body as JSON and returns the response in a given type. `patch<T>(url: string, body: any, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<T>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to edit. | | `options` | `object` | HTTP options. Optional. Default is `undefined`. | Returns `Observable<T>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with a response body in the given type. | | post() | | --- | | Constructs an observable that, when subscribed, causes the configured `POST` request to execute on the server. The server responds with the location of the replaced resource. See the individual overloads for details on the return type. | | 15 overloads... Show All Hide All Overload #1 Constructs a `POST` request that interprets the body as an `ArrayBuffer` and returns an `ArrayBuffer`. `post(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; }): Observable<ArrayBuffer>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The content to replace with. | | `options` | `object` | HTTP options. | Returns `Observable<ArrayBuffer>`: An `Observable` of the response, with the response body as an `ArrayBuffer`. Overload #2 Constructs a `POST` request that interprets the body as a `Blob` and returns the response as a `Blob`. `post(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<Blob>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The content to replace with. | | `options` | `object` | HTTP options | Returns `Observable<Blob>`: An `Observable` of the response, with the response body as a `Blob`. Overload #3 Constructs a `POST` request that interprets the body as a text string and returns the response as a string value. `post(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<string>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The content to replace with. | | `options` | `object` | HTTP options | Returns `Observable<string>`: An `Observable` of the response, with a response body of type string. Overload #4 Constructs a `POST` request that interprets the body as an `ArrayBuffer` and returns the full event stream. `post(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; }): Observable<HttpEvent<ArrayBuffer>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The content to replace with. | | `options` | `object` | HTTP options | Returns `Observable<[HttpEvent](httpevent)<ArrayBuffer>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with the response body as an `ArrayBuffer`. Overload #5 Constructs a `POST` request that interprets the body as a `Blob` and returns the response in an observable of the full event stream. `post(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<HttpEvent<Blob>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The content to replace with. | | `options` | `object` | HTTP options | Returns `Observable<[HttpEvent](httpevent)<Blob>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with the response body as `Blob`. Overload #6 Constructs a `POST` request that interprets the body as a text string and returns the full event stream. `post(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<HttpEvent<string>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The content to replace with. | | `options` | `object` | HTTP options | Returns `Observable<[HttpEvent](httpevent)<string>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with a response body of type string. Overload #7 Constructs a POST request that interprets the body as JSON and returns the full event stream. `post(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpEvent<Object>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The content to replace with. | | `options` | `object` | HTTP options | Returns `Observable<[HttpEvent](httpevent)<Object>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with a response body of type `Object`. Overload #8 Constructs a POST request that interprets the body as JSON and returns the full event stream. `post<T>(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpEvent<T>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The content to replace with. | | `options` | `object` | HTTP options | Returns `Observable<[HttpEvent](httpevent)<T>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with a response body in the requested type. Overload #9 Constructs a POST request that interprets the body as an `ArrayBuffer` and returns the full `[HttpResponse](httpresponse)`. `post(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; }): Observable<HttpResponse<ArrayBuffer>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The content to replace with. | | `options` | `object` | HTTP options | Returns `Observable<[HttpResponse](httpresponse)<ArrayBuffer>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with the response body as an `ArrayBuffer`. Overload #10 Constructs a `POST` request that interprets the body as a `Blob` and returns the full `[HttpResponse](httpresponse)`. `post(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<HttpResponse<Blob>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The content to replace with. | | `options` | `object` | HTTP options | Returns `Observable<[HttpResponse](httpresponse)<Blob>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with the response body as a `Blob`. Overload #11 Constructs a `POST` request that interprets the body as a text stream and returns the full `[HttpResponse](httpresponse)`. `post(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<HttpResponse<string>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The content to replace with. | | `options` | `object` | HTTP options | Returns `Observable<[HttpResponse](httpresponse)<string>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with a response body of type string. Overload #12 Constructs a `POST` request that interprets the body as JSON and returns the full `[HttpResponse](httpresponse)`. `post(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpResponse<Object>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The content to replace with. | | `options` | `object` | HTTP options | Returns `Observable<[HttpResponse](httpresponse)<Object>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with a response body of type `Object`. Overload #13 Constructs a `POST` request that interprets the body as JSON and returns the full `[HttpResponse](httpresponse)`. `post<T>(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpResponse<T>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The content to replace with. | | `options` | `object` | HTTP options | Returns `Observable<[HttpResponse](httpresponse)<T>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with a response body in the requested type. Overload #14 Constructs a `POST` request that interprets the body as JSON and returns the response body as an object parsed from JSON. `post(url: string, body: any, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<Object>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The content to replace with. | | `options` | `object` | HTTP options Optional. Default is `undefined`. | Returns `Observable<Object>`: An `Observable` of the response, with the response body as an object parsed from JSON. Overload #15 Constructs a `POST` request that interprets the body as JSON and returns an observable of the response. `post<T>(url: string, body: any, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<T>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The content to replace with. | | `options` | `object` | HTTP options Optional. Default is `undefined`. | Returns `Observable<T>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with a response body in the requested type. | | put() | | --- | | Constructs an observable that, when subscribed, causes the configured `PUT` request to execute on the server. The `PUT` method replaces an existing resource with a new set of values. See the individual overloads for details on the return type. | | 15 overloads... Show All Hide All Overload #1 Constructs a `PUT` request that interprets the body as an `ArrayBuffer` and returns the response as an `ArrayBuffer`. `put(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; }): Observable<ArrayBuffer>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to add/update. | | `options` | `object` | HTTP options | Returns `Observable<ArrayBuffer>`: An `Observable` of the response, with the response body as an `ArrayBuffer`. Overload #2 Constructs a `PUT` request that interprets the body as a `Blob` and returns the response as a `Blob`. `put(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<Blob>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to add/update. | | `options` | `object` | HTTP options | Returns `Observable<Blob>`: An `Observable` of the response, with the response body as a `Blob`. Overload #3 Constructs a `PUT` request that interprets the body as a text string and returns the response as a string value. `put(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<string>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to add/update. | | `options` | `object` | HTTP options | Returns `Observable<string>`: An `Observable` of the response, with a response body of type string. Overload #4 Constructs a `PUT` request that interprets the body as an `ArrayBuffer` and returns the full event stream. `put(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; }): Observable<HttpEvent<ArrayBuffer>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to add/update. | | `options` | `object` | HTTP options | Returns `Observable<[HttpEvent](httpevent)<ArrayBuffer>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with the response body as an `ArrayBuffer`. Overload #5 Constructs a `PUT` request that interprets the body as a `Blob` and returns the full event stream. `put(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<HttpEvent<Blob>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to add/update. | | `options` | `object` | HTTP options | Returns `Observable<[HttpEvent](httpevent)<Blob>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with the response body as a `Blob`. Overload #6 Constructs a `PUT` request that interprets the body as a text string and returns the full event stream. `put(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<HttpEvent<string>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to add/update. | | `options` | `object` | HTTP options | Returns `Observable<[HttpEvent](httpevent)<string>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with a response body of type string. Overload #7 Constructs a `PUT` request that interprets the body as JSON and returns the full event stream. `put(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpEvent<Object>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to add/update. | | `options` | `object` | HTTP options | Returns `Observable<[HttpEvent](httpevent)<Object>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with a response body of type `Object`. Overload #8 Constructs a `PUT` request that interprets the body as JSON and returns the full event stream. `put<T>(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpEvent<T>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to add/update. | | `options` | `object` | HTTP options | Returns `Observable<[HttpEvent](httpevent)<T>>`: An `Observable` of all `[HttpEvent](httpevent)`s for the request, with a response body in the requested type. Overload #9 Constructs a `PUT` request that interprets the body as an `ArrayBuffer` and returns an observable of the full HTTP response. `put(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCredentials?: boolean; }): Observable<HttpResponse<ArrayBuffer>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to add/update. | | `options` | `object` | HTTP options | Returns `Observable<[HttpResponse](httpresponse)<ArrayBuffer>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with the response body as an `ArrayBuffer`. Overload #10 Constructs a `PUT` request that interprets the body as a `Blob` and returns the full HTTP response. `put(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<HttpResponse<Blob>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to add/update. | | `options` | `object` | HTTP options | Returns `Observable<[HttpResponse](httpresponse)<Blob>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with the response body as a `Blob`. Overload #11 Constructs a `PUT` request that interprets the body as a text stream and returns the full HTTP response. `put(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<HttpResponse<string>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to add/update. | | `options` | `object` | HTTP options | Returns `Observable<[HttpResponse](httpresponse)<string>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with a response body of type string. Overload #12 Constructs a `PUT` request that interprets the body as JSON and returns the full HTTP response. `put(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpResponse<Object>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to add/update. | | `options` | `object` | HTTP options | Returns `Observable<[HttpResponse](httpresponse)<Object>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with a response body of type 'Object`. Overload #13 Constructs a `PUT` request that interprets the body as an instance of the requested type and returns the full HTTP response. `put<T>(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "response"; context?: HttpContext; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<HttpResponse<T>>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to add/update. | | `options` | `object` | HTTP options | Returns `Observable<[HttpResponse](httpresponse)<T>>`: An `Observable` of the `[HttpResponse](httpresponse)` for the request, with a response body in the requested type. Overload #14 Constructs a `PUT` request that interprets the body as JSON and returns an observable of JavaScript object. `put(url: string, body: any, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<Object>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to add/update. | | `options` | `object` | HTTP options Optional. Default is `undefined`. | Returns `Observable<Object>`: An `Observable` of the response as a JavaScript object. Overload #15 Constructs a `PUT` request that interprets the body as an instance of the requested type and returns an observable of the requested type. `put<T>(url: string, body: any, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<T>` Parameters | | | | | --- | --- | --- | | `url` | `string` | The endpoint URL. | | `body` | `any` | The resources to add/update. | | `options` | `object` | HTTP options Optional. Default is `undefined`. | Returns `Observable<T>`: An `Observable` of the requested type. | Usage notes ----------- Sample HTTP requests for the [Tour of Heroes](../../../tutorial/tour-of-heroes/toh-pt0) application. ### HTTP Request Example ``` // GET heroes whose name contains search term searchHeroes(term: string): observable<Hero[]>{ const params = new HttpParams({fromString: 'name=term'}); return this.httpClient.request('GET', this.heroesUrl, {responseType:'json', params}); } ``` Alternatively, the parameter string can be used without invoking HttpParams by directly joining to the URL. ``` this.httpClient.request('GET', this.heroesUrl + '?' + 'name=term', {responseType:'json'}); ``` ### JSONP Example ``` requestJsonp(url, callback = 'callback') { return this.httpClient.jsonp(this.heroesURL, callback); } ``` ### PATCH Example ``` // PATCH one of the heroes' name patchHero (id: number, heroName: string): Observable<{}> { const url = `${this.heroesUrl}/${id}`; // PATCH api/heroes/42 return this.httpClient.patch(url, {name: heroName}, httpOptions) .pipe(catchError(this.handleError('patchHero'))); } ```
programming_docs
angular HttpClientXsrfModule HttpClientXsrfModule ==================== `ngmodule` Configures XSRF protection support for outgoing requests. [See more...](httpclientxsrfmodule#description) ``` class HttpClientXsrfModule { static disable(): ModuleWithProviders<HttpClientXsrfModule> static withOptions(options: { cookieName?: string; headerName?: string; } = {}): ModuleWithProviders<HttpClientXsrfModule> } ``` Description ----------- For a server that supports a cookie-based XSRF protection system, use directly to configure XSRF protection with the correct cookie and header names. If no names are supplied, the default cookie name is `XSRF-TOKEN` and the default header name is `X-XSRF-TOKEN`. Static methods -------------- | disable() | | --- | | Disable the default XSRF protection. | | `static disable(): ModuleWithProviders<HttpClientXsrfModule>` Parameters There are no parameters. Returns `[ModuleWithProviders](../../core/modulewithproviders)<[HttpClientXsrfModule](httpclientxsrfmodule)>` | | withOptions() | | --- | | Configure XSRF protection. | | `static withOptions(options: { cookieName?: string; headerName?: string; } = {}): ModuleWithProviders<HttpClientXsrfModule>` Parameters | | | | | --- | --- | --- | | `options` | `object` | An object that can specify either or both cookie name or header name.* Cookie name default is `XSRF-TOKEN`. * Header name default is `X-XSRF-TOKEN`. Optional. Default is `{}`. | Returns `[ModuleWithProviders](../../core/modulewithproviders)<[HttpClientXsrfModule](httpclientxsrfmodule)>` | Providers --------- | Provider | | --- | | ``` HttpXsrfInterceptor ``` | | ``` { provide: HTTP_INTERCEPTORS, useExisting: HttpXsrfInterceptor, multi: true } ``` | | ``` { provide: HttpXsrfTokenExtractor, useClass: HttpXsrfCookieExtractor } ``` | | ``` withXsrfConfiguration({ cookieName: XSRF_DEFAULT_COOKIE_NAME, headerName: XSRF_DEFAULT_HEADER_NAME }).ɵproviders ``` | | ``` { provide: XSRF_ENABLED, useValue: true } ``` | angular HttpHandlerFn HttpHandlerFn ============= `type-alias` Represents the next interceptor in an interceptor chain, or the real backend if there are no further interceptors. [See more...](httphandlerfn#description) ``` type HttpHandlerFn = (req: HttpRequest<unknown>) => Observable<HttpEvent<unknown>>; ``` See also -------- * [HTTP Guide](../../../guide/http#intercepting-requests-and-responses) Description ----------- Most interceptors will delegate to this function, and either modify the outgoing request or the response when it arrives. Within the scope of the current request, however, this function may be called any number of times, for any number of downstream requests. Such downstream requests need not be to the same URL or even the same origin as the current request. It is also valid to not call the downstream handler at all, and process the current request entirely within the interceptor. This function should only be called within the scope of the request that's currently being intercepted. Once that request is complete, this downstream handler function should not be called. angular @angular/common/http/testing @angular/common/http/testing ============================ `entry-point` Supplies a testing module for the Angular HTTP subsystem. Entry point exports ------------------- ### NgModules | | | | --- | --- | | `[HttpClientTestingModule](testing/httpclienttestingmodule)` | Configures `HttpClientTestingBackend` as the `[HttpBackend](httpbackend)` used by `[HttpClient](httpclient)`. | ### Classes | | | | --- | --- | | `[HttpTestingController](testing/httptestingcontroller)` | Controller to be injected into tests, that allows for mocking and flushing of requests. | | `[TestRequest](testing/testrequest)` | A mock requests that was received and is ready to be answered. | ### Functions | | | | --- | --- | | `[provideHttpClientTesting](testing/providehttpclienttesting)` | | ### Structures | | | | --- | --- | | `[RequestMatch](testing/requestmatch)` | Defines a matcher for requests based on URL, method, or both. | angular JsonpInterceptor JsonpInterceptor ================ `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Identifies requests with the method JSONP and shifts them to the `[JsonpClientBackend](jsonpclientbackend)`. ``` class JsonpInterceptor { intercept(initialRequest: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> } ``` See also -------- * `[HttpInterceptor](httpinterceptor)` Methods ------- | intercept() | | --- | | Identifies and handles a given JSONP request. | | `intercept(initialRequest: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>` Parameters | | | | | --- | --- | --- | | `initialRequest` | `[HttpRequest](httprequest)<any>` | The outgoing request object to handle. | | `next` | `[HttpHandler](httphandler)` | The next interceptor in the chain, or the backend if no interceptors remain in the chain. | Returns `Observable<[HttpEvent](httpevent)<any>>`: An observable of the event stream. | angular HttpXhrBackend HttpXhrBackend ============== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Uses `XMLHttpRequest` to send requests to a backend server. ``` class HttpXhrBackend implements HttpBackend { handle(req: HttpRequest<any>): Observable<HttpEvent<any>> } ``` See also -------- * `[HttpHandler](httphandler)` * `[JsonpClientBackend](jsonpclientbackend)` Methods ------- | handle() | | --- | | Processes a request and returns a stream of response events. | | `handle(req: HttpRequest<any>): Observable<HttpEvent<any>>` Parameters | | | | | --- | --- | --- | | `req` | `[HttpRequest](httprequest)<any>` | The request object. | Returns `Observable<[HttpEvent](httpevent)<any>>`: An observable of the response events. | angular HttpFeature HttpFeature =========== `interface` A feature for use when configuring `[provideHttpClient](providehttpclient)`. ``` interface HttpFeature<KindT extends HttpFeatureKind> { } ``` angular HttpInterceptorFn HttpInterceptorFn ================= `type-alias` An interceptor for HTTP requests made via `[HttpClient](httpclient)`. [See more...](httpinterceptorfn#description) ``` type HttpInterceptorFn = (req: HttpRequest<unknown>, next: HttpHandlerFn) => Observable<HttpEvent<unknown>>; ``` Description ----------- `[HttpInterceptorFn](httpinterceptorfn)`s are middleware functions which `[HttpClient](httpclient)` calls when a request is made. These functions have the opportunity to modify the outgoing request or any response that comes back, as well as block, redirect, or otherwise change the request or response semantics. An `[HttpHandlerFn](httphandlerfn)` representing the next interceptor (or the backend which will make a real HTTP request) is provided. Most interceptors will delegate to this function, but that is not required (see `[HttpHandlerFn](httphandlerfn)` for more details). `[HttpInterceptorFn](httpinterceptorfn)`s have access to `inject()` via the `[EnvironmentInjector](../../core/environmentinjector)` from which they were configured. angular HttpSentEvent HttpSentEvent ============= `interface` An event indicating that the request was sent to the server. Useful when a request may be retried multiple times, to distinguish between retries on the final event stream. ``` interface HttpSentEvent { type: HttpEventType.Sent } ``` Properties ---------- | Property | Description | | --- | --- | | `type: [HttpEventType.Sent](httpeventtype#Sent)` | | angular HttpRequest HttpRequest =========== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An outgoing HTTP request with an optional typed body. [See more...](httprequest#description) ``` class HttpRequest<T> { constructor(method: string, url: string, third?: T | { headers?: HttpHeaders; context?: HttpContext; reportProgress?: boolean; params?: HttpParams; responseType?: "arraybuffer" | "blob" | "text" | "json"; withCredentials?: boolean; }, fourth?: { headers?: HttpHeaders; context?: HttpContext; reportProgress?: boolean; params?: HttpParams; responseType?: "arraybuffer" | "blob" | "text" | "json"; withCredentials?: boolean; }) body: T | null headers: HttpHeaders context: HttpContext reportProgress: boolean withCredentials: boolean responseType: 'arraybuffer' | 'blob' | 'json' | 'text' method: string params: HttpParams urlWithParams: string url: string serializeBody(): ArrayBuffer | Blob | FormData | string | null detectContentTypeHeader(): string | null clone(update: { headers?: HttpHeaders; context?: HttpContext; reportProgress?: boolean; params?: HttpParams; responseType?: "arraybuffer" | "blob" | "text" | "json"; ... 5 more ...; setParams?: { ...; }; } = {}): HttpRequest<any> } ``` Description ----------- `[HttpRequest](httprequest)` represents an outgoing request, including URL, method, headers, body, and other request configuration options. Instances should be assumed to be immutable. To modify a `[HttpRequest](httprequest)`, the `clone` method should be used. Constructor ----------- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 3 overloads... Show All Hide All Overload #1 `constructor(method: "DELETE" | "GET" | "HEAD" | "JSONP" | "OPTIONS", url: string, init?: { headers?: HttpHeaders; context?: HttpContext; reportProgress?: boolean; params?: HttpParams; responseType?: "arraybuffer" | "blob" | "text" | "json"; withCredentials?: boolean; })` Parameters | | | | | --- | --- | --- | | `method` | `"DELETE" | "GET" | "HEAD" | "JSONP" | "OPTIONS"` | | | `url` | `string` | | | `init` | `object` | Optional. Default is `undefined`. | Overload #2 `constructor(method: "POST" | "PUT" | "PATCH", url: string, body: T, init?: { headers?: HttpHeaders; context?: HttpContext; reportProgress?: boolean; params?: HttpParams; responseType?: "arraybuffer" | "blob" | "text" | "json"; withCredentials?: boolean; })` Parameters | | | | | --- | --- | --- | | `method` | `"POST" | "PUT" | "PATCH"` | | | `url` | `string` | | | `body` | `T` | | | `init` | `object` | Optional. Default is `undefined`. | Overload #3 `constructor(method: string, url: string, body: T, init?: { headers?: HttpHeaders; context?: HttpContext; reportProgress?: boolean; params?: HttpParams; responseType?: "arraybuffer" | "blob" | "text" | "json"; withCredentials?: boolean; })` Parameters | | | | | --- | --- | --- | | `method` | `string` | | | `url` | `string` | | | `body` | `T` | | | `init` | `object` | Optional. Default is `undefined`. | | Properties ---------- | Property | Description | | --- | --- | | `body: T | null` | Read-Only The request body, or `null` if one isn't set. Bodies are not enforced to be immutable, as they can include a reference to any user-defined data type. However, interceptors should take care to preserve idempotence by treating them as such. | | `headers: [HttpHeaders](httpheaders)` | Read-Only Outgoing headers for this request. | | `context: [HttpContext](httpcontext)` | Read-Only Shared and mutable context that can be used by interceptors | | `reportProgress: boolean` | Read-Only Whether this request should be made in a way that exposes progress events. Progress events are expensive (change detection runs on each event) and so they should only be requested if the consumer intends to monitor them. | | `withCredentials: boolean` | Read-Only Whether this request should be sent with outgoing credentials (cookies). | | `responseType: 'arraybuffer' | 'blob' | 'json' | 'text'` | Read-Only The expected response type of the server. This is used to parse the response appropriately before returning it to the requestee. | | `method: string` | Read-Only The outgoing HTTP request method. | | `params: [HttpParams](httpparams)` | Read-Only Outgoing URL parameters. To pass a string representation of HTTP parameters in the URL-query-string format, the `[HttpParamsOptions](httpparamsoptions)`' `fromString` may be used. For example: ``` new HttpParams({fromString: 'angular=awesome'}) ``` | | `urlWithParams: string` | Read-Only The outgoing URL with all URL parameters set. | | `url: string` | Read-Only Declared in Constructor | Methods ------- | serializeBody() | | --- | | Transform the free-form body into a serialized format suitable for transmission to the server. | | `serializeBody(): ArrayBuffer | Blob | FormData | string | null` Parameters There are no parameters. Returns `ArrayBuffer | Blob | FormData | string | null` | | detectContentTypeHeader() | | --- | | Examine the body and attempt to infer an appropriate MIME type for it. | | `detectContentTypeHeader(): string | null` Parameters There are no parameters. Returns `string | null` | | If no such type can be inferred, this method will return `null`. | | clone() | | --- | | 3 overloads... Show All Hide All Overload #1 `clone(): HttpRequest<T>` Parameters There are no parameters. Returns `[HttpRequest<T>](httprequest)` Overload #2 `clone(update: { headers?: HttpHeaders; context?: HttpContext; reportProgress?: boolean; params?: HttpParams; responseType?: "arraybuffer" | "blob" | "text" | "json"; ... 5 more ...; setParams?: { ...; }; }): HttpRequest<T>` Parameters | | | | | --- | --- | --- | | `update` | `object` | | Returns `[HttpRequest<T>](httprequest)` Overload #3 `clone<V>(update: { headers?: HttpHeaders; context?: HttpContext; reportProgress?: boolean; params?: HttpParams; responseType?: "arraybuffer" | "blob" | "text" | "json"; ... 5 more ...; setParams?: { ...; }; }): HttpRequest<V>` Parameters | | | | | --- | --- | --- | | `update` | `object` | | Returns `[HttpRequest](httprequest)<V>` | angular HttpUploadProgressEvent HttpUploadProgressEvent ======================= `interface` An upload progress event. ``` interface HttpUploadProgressEvent extends HttpProgressEvent { type: HttpEventType.UploadProgress // inherited from common/http/HttpProgressEvent type: HttpEventType.DownloadProgress | HttpEventType.UploadProgress loaded: number total?: number } ``` Properties ---------- | Property | Description | | --- | --- | | `type: [HttpEventType.UploadProgress](httpeventtype#UploadProgress)` | | angular HttpFeatureKind HttpFeatureKind =============== `enum` Identifies a particular kind of `[HttpFeature](httpfeature)`. ``` enum HttpFeatureKind { Interceptors LegacyInterceptors CustomXsrfConfiguration NoXsrfProtection JsonpSupport RequestsMadeViaParent } ``` Members ------- | Member | Description | | --- | --- | | `Interceptors` | | | `LegacyInterceptors` | | | `CustomXsrfConfiguration` | | | `NoXsrfProtection` | | | `JsonpSupport` | | | `RequestsMadeViaParent` | | angular HttpResponse HttpResponse ============ `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A full HTTP response, including a typed response body (which may be `null` if one was not returned). [See more...](httpresponse#description) ``` class HttpResponse<T> extends HttpResponseBase { constructor(init: { body?: T; headers?: HttpHeaders; status?: number; statusText?: string; url?: string; } = {}) body: T | null type: HttpEventType.Response clone(update: { body?: any; headers?: HttpHeaders; status?: number; statusText?: string; url?: string; } = {}): HttpResponse<any> // inherited from common/http/HttpResponseBase constructor(init: { headers?: HttpHeaders; status?: number; statusText?: string; url?: string; }, defaultStatus: number = HttpStatusCode.Ok, defaultStatusText: string = 'OK') headers: HttpHeaders status: number statusText: string url: string | null ok: boolean type: HttpEventType.Response | HttpEventType.ResponseHeader } ``` Description ----------- `[HttpResponse](httpresponse)` is a `[HttpEvent](httpevent)` available on the response event stream. Constructor ----------- | | | --- | | Construct a new `[HttpResponse](httpresponse)`. This class is "final" and should not be extended. See the [public API notes](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes). | | `constructor(init: { body?: T; headers?: HttpHeaders; status?: number; statusText?: string; url?: string; } = {})` Parameters | | | | | --- | --- | --- | | `init` | `object` | Optional. Default is `{}`. | | Properties ---------- | Property | Description | | --- | --- | | `body: T | null` | Read-Only The response body, or `null` if one was not returned. | | `type: [HttpEventType.Response](httpeventtype#Response)` | Read-Only | Methods ------- | clone() | | --- | | 3 overloads... Show All Hide All Overload #1 `clone(): HttpResponse<T>` Parameters There are no parameters. Returns `[HttpResponse<T>](httpresponse)` Overload #2 `clone(update: { headers?: HttpHeaders; status?: number; statusText?: string; url?: string; }): HttpResponse<T>` Parameters | | | | | --- | --- | --- | | `update` | `object` | | Returns `[HttpResponse<T>](httpresponse)` Overload #3 `clone<V>(update: { body?: V; headers?: HttpHeaders; status?: number; statusText?: string; url?: string; }): HttpResponse<V>` Parameters | | | | | --- | --- | --- | | `update` | `object` | | Returns `[HttpResponse](httpresponse)<V>` | angular HttpInterceptor HttpInterceptor =============== `interface` Intercepts and handles an `[HttpRequest](httprequest)` or `[HttpResponse](httpresponse)`. [See more...](httpinterceptor#description) ``` interface HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> } ``` See also -------- * [HTTP Guide](../../../guide/http#intercepting-requests-and-responses) Description ----------- Most interceptors transform the outgoing request before passing it to the next interceptor in the chain, by calling `next.handle(transformedReq)`. An interceptor may transform the response event stream as well, by applying additional RxJS operators on the stream returned by `next.handle()`. More rarely, an interceptor may handle the request entirely, and compose a new event stream instead of invoking `next.handle()`. This is an acceptable behavior, but keep in mind that further interceptors will be skipped entirely. It is also rare but valid for an interceptor to return multiple responses on the event stream for a single request. Further information is available in the [Usage Notes...](httpinterceptor#usage-notes) Methods ------- | intercept() | | --- | | Identifies and handles a given HTTP request. | | `intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>` Parameters | | | | | --- | --- | --- | | `req` | `[HttpRequest](httprequest)<any>` | The outgoing request object to handle. | | `next` | `[HttpHandler](httphandler)` | The next interceptor in the chain, or the backend if no interceptors remain in the chain. | Returns `Observable<[HttpEvent](httpevent)<any>>`: An observable of the event stream. | Usage notes ----------- To use the same instance of `HttpInterceptors` for the entire app, import the `[HttpClientModule](httpclientmodule)` only in your `AppModule`, and add the interceptors to the root application injector. If you import `[HttpClientModule](httpclientmodule)` multiple times across different modules (for example, in lazy loading modules), each import creates a new copy of the `[HttpClientModule](httpclientmodule)`, which overwrites the interceptors provided in the root module.
programming_docs
angular RequestMatch RequestMatch ============ `interface` Defines a matcher for requests based on URL, method, or both. ``` interface RequestMatch { method?: string url?: string } ``` Properties ---------- | Property | Description | | --- | --- | | `method?: string` | | | `url?: string` | | angular HttpClientTestingModule HttpClientTestingModule ======================= `ngmodule` Configures `HttpClientTestingBackend` as the `[HttpBackend](../httpbackend)` used by `[HttpClient](../httpclient)`. [See more...](httpclienttestingmodule#description) ``` class HttpClientTestingModule { } ``` Description ----------- Inject `[HttpTestingController](httptestingcontroller)` to expect and flush requests in your tests. Providers --------- | Provider | | --- | | ``` provideHttpClientTesting() ``` | angular HttpTestingController HttpTestingController ===================== `class` Controller to be injected into tests, that allows for mocking and flushing of requests. ``` abstract class HttpTestingController { abstract match(match: string | RequestMatch | ((req: HttpRequest<any>) => boolean)): TestRequest[] abstract expectOne(url: string, description?: string): TestRequest abstract expectNone(url: string, description?: string): void abstract verify(opts?: { ignoreCancelled?: boolean; }): void } ``` Methods ------- | match() | | --- | | Search for requests that match the given parameter, without any expectations. | | `abstract match(match: string | RequestMatch | ((req: HttpRequest<any>) => boolean)): TestRequest[]` Parameters | | | | | --- | --- | --- | | `match` | `string | [RequestMatch](requestmatch) | ((req: [HttpRequest](../httprequest)<any>) => boolean)` | | Returns `[TestRequest](testrequest)[]` | | expectOne() | | --- | | Expect that a single request has been made which matches the given URL, and return its mock. | | 3 overloads... Show All Hide All `abstract expectOne(url: string, description?: string): TestRequest` Parameters | | | | | --- | --- | --- | | `url` | `string` | | | `description` | `string` | Optional. Default is `undefined`. | Returns `[TestRequest](testrequest)` Overload #1 Expect that a single request has been made which matches the given parameters, and return its mock. `abstract expectOne(params: RequestMatch, description?: string): TestRequest` Parameters | | | | | --- | --- | --- | | `params` | `[RequestMatch](requestmatch)` | | | `description` | `string` | Optional. Default is `undefined`. | Returns `[TestRequest](testrequest)` Overload #2 Expect that a single request has been made which matches the given predicate function, and return its mock. `abstract expectOne(matchFn: (req: HttpRequest<any>) => boolean, description?: string): TestRequest` Parameters | | | | | --- | --- | --- | | `matchFn` | `(req: [HttpRequest](../httprequest)<any>) => boolean` | | | `description` | `string` | Optional. Default is `undefined`. | Returns `[TestRequest](testrequest)` Overload #3 Expect that a single request has been made which matches the given condition, and return its mock. `abstract expectOne(match: string | RequestMatch | ((req: HttpRequest<any>) => boolean), description?: string): TestRequest` Parameters | | | | | --- | --- | --- | | `match` | `string | [RequestMatch](requestmatch) | ((req: [HttpRequest](../httprequest)<any>) => boolean)` | | | `description` | `string` | Optional. Default is `undefined`. | Returns `[TestRequest](testrequest)` | | If no such request has been made, or more than one such request has been made, fail with an error message including the given request description, if any. | | expectNone() | | --- | | Expect that no requests have been made which match the given URL. | | 3 overloads... Show All Hide All `abstract expectNone(url: string, description?: string): void` Parameters | | | | | --- | --- | --- | | `url` | `string` | | | `description` | `string` | Optional. Default is `undefined`. | Returns `void` Overload #1 Expect that no requests have been made which match the given parameters. `abstract expectNone(params: RequestMatch, description?: string): void` Parameters | | | | | --- | --- | --- | | `params` | `[RequestMatch](requestmatch)` | | | `description` | `string` | Optional. Default is `undefined`. | Returns `void` Overload #2 Expect that no requests have been made which match the given predicate function. `abstract expectNone(matchFn: (req: HttpRequest<any>) => boolean, description?: string): void` Parameters | | | | | --- | --- | --- | | `matchFn` | `(req: [HttpRequest](../httprequest)<any>) => boolean` | | | `description` | `string` | Optional. Default is `undefined`. | Returns `void` Overload #3 Expect that no requests have been made which match the given condition. `abstract expectNone(match: string | RequestMatch | ((req: HttpRequest<any>) => boolean), description?: string): void` Parameters | | | | | --- | --- | --- | | `match` | `string | [RequestMatch](requestmatch) | ((req: [HttpRequest](../httprequest)<any>) => boolean)` | | | `description` | `string` | Optional. Default is `undefined`. | Returns `void` | | If a matching request has been made, fail with an error message including the given request description, if any. | | verify() | | --- | | Verify that no unmatched requests are outstanding. | | `abstract verify(opts?: { ignoreCancelled?: boolean; }): void` Parameters | | | | | --- | --- | --- | | `opts` | `object` | Optional. Default is `undefined`. | Returns `void` | | If any requests are outstanding, fail with an error message indicating which requests were not handled. If `ignoreCancelled` is not set (the default), `verify()` will also fail if cancelled requests were not explicitly matched. | angular provideHttpClientTesting provideHttpClientTesting ======================== `function` ### `provideHttpClientTesting(): Provider[]` ###### Parameters There are no parameters. ###### Returns `[Provider](../../../core/provider)[]` angular TestRequest TestRequest =========== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A mock requests that was received and is ready to be answered. [See more...](testrequest#description) ``` class TestRequest { constructor(request: HttpRequest<any>, observer: Observer<HttpEvent<any>>) cancelled: boolean request: HttpRequest<any> flush(body: string | number | boolean | Object | ArrayBuffer | Blob | (string | number | boolean | Object)[], opts: { headers?: HttpHeaders | { [name: string]: string | string[]; }; status?: number; statusText?: string; } = {}): void error(error: ErrorEvent | ProgressEvent<EventTarget>, opts: TestRequestErrorOptions = {}): void event(event: HttpEvent<any>): void } ``` Description ----------- This interface allows access to the underlying `[HttpRequest](../httprequest)`, and allows responding with `[HttpEvent](../httpevent)`s or `[HttpErrorResponse](../httperrorresponse)`s. Constructor ----------- | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | | `constructor(request: HttpRequest<any>, observer: Observer<HttpEvent<any>>)` Parameters | | | | | --- | --- | --- | | `request` | `[HttpRequest](../httprequest)<any>` | | | `observer` | `Observer<[HttpEvent](../httpevent)<any>>` | | | Properties ---------- | Property | Description | | --- | --- | | `cancelled: boolean` | Read-Only Whether the request was cancelled after it was sent. | | `request: [HttpRequest](../httprequest)<any>` | Declared in Constructor | Methods ------- | flush() | | --- | | Resolve the request by returning a body plus additional HTTP information (such as response headers) if provided. If the request specifies an expected body type, the body is converted into the requested type. Otherwise, the body is converted to `JSON` by default. | | `flush(body: string | number | boolean | Object | ArrayBuffer | Blob | (string | number | boolean | Object)[], opts: { headers?: HttpHeaders | { [name: string]: string | string[]; }; status?: number; statusText?: string; } = {}): void` Parameters | | | | | --- | --- | --- | | `body` | `string | number | boolean | Object | ArrayBuffer | Blob | (string | number | boolean | Object)[]` | | | `opts` | `object` | Optional. Default is `{}`. | Returns `void` | | Both successful and unsuccessful responses can be delivered via `[flush](../../../core/testing/flush)()`. | | error() | | --- | | Resolve the request by returning an `ErrorEvent` (e.g. simulating a network failure). `error(error: ErrorEvent, opts?: TestRequestErrorOptions): void` **Deprecated** Http requests never emit an `ErrorEvent`. Please specify a `ProgressEvent`. Parameters | | | | | --- | --- | --- | | `error` | `ErrorEvent` | | | `opts` | `TestRequestErrorOptions` | Optional. Default is `undefined`. | Returns `void` | | Resolve the request by returning an `ProgressEvent` (e.g. simulating a network failure). `error(error: ProgressEvent<EventTarget>, opts?: TestRequestErrorOptions): void` Parameters | | | | | --- | --- | --- | | `error` | `ProgressEvent<EventTarget>` | | | `opts` | `TestRequestErrorOptions` | Optional. Default is `undefined`. | Returns `void` | | event() | | --- | | Deliver an arbitrary `[HttpEvent](../httpevent)` (such as a progress event) on the response stream for this request. | | `event(event: HttpEvent<any>): void` Parameters | | | | | --- | --- | --- | | `event` | `[HttpEvent](../httpevent)<any>` | | Returns `void` | angular NgElementStrategyFactory NgElementStrategyFactory ======================== `interface` Factory used to create new strategies for each NgElement instance. ``` interface NgElementStrategyFactory { create(injector: Injector): NgElementStrategy } ``` Methods ------- | create() | | --- | | Creates a new instance to be used for an NgElement. | | `create(injector: Injector): NgElementStrategy` Parameters | | | | | --- | --- | --- | | `injector` | `[Injector](../core/injector)` | | Returns `[NgElementStrategy](ngelementstrategy)` | angular createCustomElement createCustomElement =================== `function` Creates a custom element class based on an Angular component. [See more...](createcustomelement#description) ### `createCustomElement<P>(component: Type<any>, config: NgElementConfig): NgElementConstructor<P>` ###### Parameters | | | | | --- | --- | --- | | `component` | `[Type](../core/type)<any>` | The component to transform. | | `config` | `[NgElementConfig](ngelementconfig)` | A configuration that provides initialization information to the created class. | ###### Returns `[NgElementConstructor<P>](ngelementconstructor)`: The custom-element construction class, which can be registered with a browser's `CustomElementRegistry`. See also -------- * [Angular Elements Overview](../../guide/elements "Turning Angular components into custom elements") Description ----------- Builds a class that encapsulates the functionality of the provided component and uses the configuration information to provide more context to the class. Takes the component factory's inputs and outputs to convert them to the proper custom element API and add hooks to input changes. The configuration's injector is the initial injector set on the class, and used by default for each created instance.This behavior can be overridden with the static property to affect all newly created instances, or as a constructor argument for one-off creations. angular NgElementStrategy NgElementStrategy ================= `interface` Underlying strategy used by the NgElement to create/destroy the component and react to input changes. ``` interface NgElementStrategy { events: Observable<NgElementStrategyEvent> connect(element: HTMLElement): void disconnect(): void getInputValue(propName: string): any setInputValue(propName: string, value: string): void } ``` Properties ---------- | Property | Description | | --- | --- | | `events: Observable<[NgElementStrategyEvent](ngelementstrategyevent)>` | | Methods ------- | connect() | | --- | | `connect(element: HTMLElement): void` Parameters | | | | | --- | --- | --- | | `element` | `HTMLElement` | | Returns `void` | | disconnect() | | --- | | `disconnect(): void` Parameters There are no parameters. Returns `void` | | getInputValue() | | --- | | `getInputValue(propName: string): any` Parameters | | | | | --- | --- | --- | | `propName` | `string` | | Returns `any` | | setInputValue() | | --- | | `setInputValue(propName: string, value: string): void` Parameters | | | | | --- | --- | --- | | `propName` | `string` | | | `value` | `string` | | Returns `void` | angular NgElement NgElement ========= `class` Implements the functionality needed for a custom element. ``` abstract class NgElement extends HTMLElement { protected abstract ngElementStrategy: NgElementStrategy protected ngElementEventsSubscription: Subscription | null abstract attributeChangedCallback(attrName: string, oldValue: string, newValue: string, namespace?: string): void abstract connectedCallback(): void abstract disconnectedCallback(): void } ``` Properties ---------- | Property | Description | | --- | --- | | `protected abstract ngElementStrategy: [NgElementStrategy](ngelementstrategy)` | The strategy that controls how a component is transformed in a custom element. | | `protected ngElementEventsSubscription: Subscription | null` | A subscription to change, connect, and disconnect events in the custom element. | Methods ------- | attributeChangedCallback() | | --- | | Prototype for a handler that responds to a change in an observed attribute. | | `abstract attributeChangedCallback(attrName: string, oldValue: string, newValue: string, namespace?: string): void` Parameters | | | | | --- | --- | --- | | `attrName` | `string` | The name of the attribute that has changed. | | `oldValue` | `string` | The previous value of the attribute. | | `newValue` | `string` | The new value of the attribute. | | `namespace` | `string` | The namespace in which the attribute is defined. Optional. Default is `undefined`. | Returns `void`: Nothing. | | connectedCallback() | | --- | | Prototype for a handler that responds to the insertion of the custom element in the DOM. | | `abstract connectedCallback(): void` Parameters There are no parameters. Returns `void`: Nothing. | | disconnectedCallback() | | --- | | Prototype for a handler that responds to the deletion of the custom element from the DOM. | | `abstract disconnectedCallback(): void` Parameters There are no parameters. Returns `void`: Nothing. | angular WithProperties WithProperties ============== `type-alias` Additional type information that can be added to the NgElement class, for properties that are added based on the inputs and methods of the underlying component. ``` type WithProperties<P> = { [property in keyof P]: P[property]; }; ``` angular NgElementConfig NgElementConfig =============== `interface` A configuration that initializes an NgElementConstructor with the dependencies and strategy it needs to transform a component into a custom element class. ``` interface NgElementConfig { injector: Injector strategyFactory?: NgElementStrategyFactory } ``` Properties ---------- | Property | Description | | --- | --- | | `injector: [Injector](../core/injector)` | The injector to use for retrieving the component's factory. | | `strategyFactory?: [NgElementStrategyFactory](ngelementstrategyfactory)` | An optional custom strategy factory to use instead of the default. The strategy controls how the transformation is performed. | angular NgElementConstructor NgElementConstructor ==================== `interface` Prototype for a class constructor based on an Angular component that can be used for custom element registration. Implemented and returned by the [createCustomElement() function](createcustomelement). ``` interface NgElementConstructor<P> { observedAttributes: string[] new (injector?: Injector): NgElement & WithProperties<P> } ``` See also -------- * [Angular Elements Overview](../../guide/elements "Turning Angular components into custom elements") Properties ---------- | Property | Description | | --- | --- | | `observedAttributes: string[]` | Read-Only An array of observed attribute names for the custom element, derived by transforming input property names from the source component. | Methods ------- | *construct signature* | | --- | | Initializes a constructor instance. | | `new (injector?: Injector): NgElement & WithProperties<P>` Parameters | | | | | --- | --- | --- | | `injector` | `[Injector](../core/injector)` | If provided, overrides the configured injector. Optional. Default is `undefined`. | Returns `[NgElement](ngelement) & [WithProperties](withproperties)<P>` | angular NgElementStrategyEvent NgElementStrategyEvent ====================== `interface` Interface for the events emitted through the NgElementStrategy. ``` interface NgElementStrategyEvent { name: string value: any } ``` Properties ---------- | Property | Description | | --- | --- | | `name: string` | | | `value: any` | | angular RESOURCE_CACHE_PROVIDER RESOURCE\_CACHE\_PROVIDER ========================= `const` `deprecated` **Deprecated:** This was previously necessary in some cases to test AOT-compiled components with View Engine, but is no longer since Ivy. ### `const RESOURCE_CACHE_PROVIDER: Provider[];` angular platformBrowserDynamic platformBrowserDynamic ====================== `const` ### `const platformBrowserDynamic: (extraProviders?: StaticProvider[]) => PlatformRef;` angular JitCompilerFactory JitCompilerFactory ================== `class` `deprecated` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` **Deprecated:** Ivy JIT mode doesn't require accessing this symbol. See [JIT API changes due to ViewEngine deprecation](../../guide/deprecations#jit-api-changes) for additional context. ``` class JitCompilerFactory implements CompilerFactory { constructor(defaultOptions: CompilerOptions[]) createCompiler(options: CompilerOptions[] = []): Compiler } ``` Constructor ----------- | | | | | | --- | --- | --- | --- | | `constructor(defaultOptions: CompilerOptions[])` Parameters | | | | | --- | --- | --- | | `defaultOptions` | `[CompilerOptions](../core/compileroptions)[]` | | | Methods ------- | createCompiler() | | --- | | `createCompiler(options: CompilerOptions[] = []): Compiler` Parameters | | | | | --- | --- | --- | | `options` | `[CompilerOptions](../core/compileroptions)[]` | Optional. Default is `[]`. | Returns `[Compiler](../core/compiler)` | angular @angular/platform-browser-dynamic/testing @angular/platform-browser-dynamic/testing ========================================= `entry-point` Supplies a testing module for the Angular JIT platform-browser subsystem. Entry point exports ------------------- ### NgModules | | | | --- | --- | | `[BrowserDynamicTestingModule](testing/browserdynamictestingmodule)` | NgModule for testing. | ### Types | | | | --- | --- | | `[platformBrowserDynamicTesting](testing/platformbrowserdynamictesting)` | | angular BrowserDynamicTestingModule BrowserDynamicTestingModule =========================== `ngmodule` NgModule for testing. ``` class BrowserDynamicTestingModule { } ``` Providers --------- | Provider | | --- | | ``` { provide: TestComponentRenderer, useClass: DOMTestComponentRenderer } ``` | angular platformBrowserDynamicTesting platformBrowserDynamicTesting ============================= `const` ### `const platformBrowserDynamicTesting: (extraProviders?: StaticProvider[]) => PlatformRef;`
programming_docs
angular NoopAnimationPlayer NoopAnimationPlayer =================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An empty programmatic controller for reusable animations. Used internally when animations are disabled, to avoid checking for the null case when an animation player is expected. ``` class NoopAnimationPlayer implements AnimationPlayer { constructor(duration: number = 0, delay: number = 0) parentPlayer: AnimationPlayer | null totalTime: number onStart(fn: () => void): void onDone(fn: () => void): void onDestroy(fn: () => void): void hasStarted(): boolean init(): void play(): void pause(): void restart(): void finish(): void destroy(): void reset(): void setPosition(position: number): void getPosition(): number } ``` Subclasses ---------- * `[MockAnimationPlayer](browser/testing/mockanimationplayer)` See also -------- * `<animate>()` * `[AnimationPlayer](animationplayer)` * `GroupPlayer` Constructor ----------- | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | | `constructor(duration: number = 0, delay: number = 0)` Parameters | | | | | --- | --- | --- | | `duration` | `number` | Optional. Default is `0`. | | `delay` | `number` | Optional. Default is `0`. | | Properties ---------- | Property | Description | | --- | --- | | `parentPlayer: [AnimationPlayer](animationplayer) | null` | | | `totalTime: number` | Read-Only | Methods ------- | onStart() | | --- | | `onStart(fn: () => void): void` Parameters | | | | | --- | --- | --- | | `fn` | `() => void` | | Returns `void` | | onDone() | | --- | | `onDone(fn: () => void): void` Parameters | | | | | --- | --- | --- | | `fn` | `() => void` | | Returns `void` | | onDestroy() | | --- | | `onDestroy(fn: () => void): void` Parameters | | | | | --- | --- | --- | | `fn` | `() => void` | | Returns `void` | | hasStarted() | | --- | | `hasStarted(): boolean` Parameters There are no parameters. Returns `boolean` | | init() | | --- | | `init(): void` Parameters There are no parameters. Returns `void` | | play() | | --- | | `play(): void` Parameters There are no parameters. Returns `void` | | pause() | | --- | | `pause(): void` Parameters There are no parameters. Returns `void` | | restart() | | --- | | `restart(): void` Parameters There are no parameters. Returns `void` | | finish() | | --- | | `finish(): void` Parameters There are no parameters. Returns `void` | | destroy() | | --- | | `destroy(): void` Parameters There are no parameters. Returns `void` | | reset() | | --- | | `reset(): void` Parameters There are no parameters. Returns `void` | | setPosition() | | --- | | `setPosition(position: number): void` Parameters | | | | | --- | --- | --- | | `position` | `number` | | Returns `void` | | getPosition() | | --- | | `getPosition(): number` Parameters There are no parameters. Returns `number` | angular transition transition ========== `function` Declares an animation transition which is played when a certain specified condition is met. ### `transition(stateChangeExpr: string | ((fromState: string, toState: string, element?: any, params?: { [key: string]: any; }) => boolean), steps: AnimationMetadata | AnimationMetadata[], options: AnimationOptions = null): AnimationTransitionMetadata` ###### Parameters | | | | | --- | --- | --- | | `stateChangeExpr` | `string | ((fromState: string, toState: string, element?: any, params?: { [key: string]: any; }) => boolean)` | A string with a specific format or a function that specifies when the animation transition should occur (see [State Change Expression](transition#state-change-expression)). | | `steps` | `[AnimationMetadata](animationmetadata) | [AnimationMetadata](animationmetadata)[]` | One or more animation objects that represent the animation's instructions. | | `options` | `[AnimationOptions](animationoptions)` | An options object that can be used to specify a delay for the animation or provide custom parameters for it. Optional. Default is `null`. | ###### Returns `[AnimationTransitionMetadata](animationtransitionmetadata)`: An object that encapsulates the transition data. Usage notes ----------- ### State Change Expression The State Change Expression instructs Angular when to run the transition's animations, it can either be * a string with a specific syntax * or a function that compares the previous and current state (value of the expression bound to the element's trigger) and returns `true` if the transition should occur or `false` otherwise The string format can be: * `fromState => toState`, which indicates that the transition's animations should occur then the expression bound to the trigger's element goes from `fromState` to `toState` *Example:* ``` transition('open => closed', animate('.5s ease-out', style({ height: 0 }) )) ``` * `fromState <=> toState`, which indicates that the transition's animations should occur then the expression bound to the trigger's element goes from `fromState` to `toState` or vice versa *Example:* ``` transition('enabled <=> disabled', animate('1s cubic-bezier(0.8,0.3,0,1)')) ``` * `:enter`/`:leave`, which indicates that the transition's animations should occur when the element enters or exists the DOM *Example:* ``` transition(':enter', [ style({ opacity: 0 }), animate('500ms', style({ opacity: 1 })) ]) ``` * `:increment`/`:decrement`, which indicates that the transition's animations should occur when the numerical expression bound to the trigger's element has increased in value or decreased *Example:* ``` transition(':increment', query('@counter', animateChild())) ``` * a sequence of any of the above divided by commas, which indicates that transition's animations should occur whenever one of the state change expressions matches *Example:* ``` transition(':increment, * => enabled, :enter', animate('1s ease', keyframes([ style({ transform: 'scale(1)', offset: 0}), style({ transform: 'scale(1.1)', offset: 0.7}), style({ transform: 'scale(1)', offset: 1}) ]))), ``` Also note that in such context: * `void` can be used to indicate the absence of the element * asterisks can be used as wildcards that match any state * (as a consequence of the above, `void => *` is equivalent to `:enter` and `* => void` is equivalent to `:leave`) * `true` and `false` also match expression values of `1` and `0` respectively (but do not match *truthy* and *falsy* values) > Be careful about entering end leaving elements as their transitions present a common pitfall for developers. > > Note that when an element with a trigger enters the DOM its `:enter` transition always gets executed, but its `:leave` transition will not be executed if the element is removed alongside its parent (as it will be removed "without warning" before its transition has a chance to be executed, the only way that such transition can occur is if the element is exiting the DOM on its own). > > ### Animating to a Final State If the final step in a transition is a call to `<animate>()` that uses a timing value with no `<style>` data, that step is automatically considered the final animation arc, for the element to reach the final state, in such case Angular automatically adds or removes CSS styles to ensure that the element is in the correct final state. ### Usage Examples * Transition animations applied based on the trigger's expression value ``` <div [@myAnimationTrigger]="myStatusExp"> ... </div> ``` ``` trigger("myAnimationTrigger", [ ..., // states transition("on => off, open => closed", animate(500)), transition("* <=> error", query('.indicator', animateChild())) ]) ``` * Transition animations applied based on custom logic dependent on the trigger's expression value and provided parameters ``` <div [@myAnimationTrigger]="{ value: stepName, params: { target: currentTarget } }"> ... </div> ``` ``` trigger("myAnimationTrigger", [ ..., // states transition( (fromState, toState, _element, params) => ['firststep', 'laststep'].includes(fromState.toLowerCase()) && toState === params?.['target'], animate('1s') ) ]) ``` angular AnimationQueryOptions AnimationQueryOptions ===================== `interface` Encapsulates animation query options. Passed to the `<query>()` function. ``` interface AnimationQueryOptions extends AnimationOptions { optional?: boolean limit?: number // inherited from animations/AnimationOptions delay?: number | string params?: {...} } ``` Properties ---------- | Property | Description | | --- | --- | | `optional?: boolean` | True if this query is optional, false if it is required. Default is false. A required query throws an error if no elements are retrieved when the query is executed. An optional query does not. | | `limit?: number` | A maximum total number of results to return from the query. If negative, results are limited from the end of the query list towards the beginning. By default, results are not limited. | angular @angular/animations/browser @angular/animations/browser =========================== `entry-point` Provides infrastructure for cross-platform rendering of animations in a browser. Entry point exports ------------------- ### Classes | | | | --- | --- | | `[AnimationDriver](browser/animationdriver)` | | angular AnimationStateMetadata AnimationStateMetadata ====================== `interface` Encapsulates an animation state by associating a state name with a set of CSS styles. Instantiated and returned by the [`state()`](state) function. ``` interface AnimationStateMetadata extends AnimationMetadata { name: string styles: AnimationStyleMetadata options?: {...} // inherited from animations/AnimationMetadata type: AnimationMetadataType } ``` Properties ---------- | Property | Description | | --- | --- | | `name: string` | The state name, unique within the component. | | `styles: [AnimationStyleMetadata](animationstylemetadata)` | The CSS styles associated with this state. | | `options?: { params: { [name: string]: any; }; }` | An options object containing developer-defined parameters that provide styling defaults and can be overridden on invocation. | angular AnimationEvent AnimationEvent ============== `interface` An instance of this class is returned as an event parameter when an animation callback is captured for an animation either during the start or done phase. [See more...](animationevent#description) ``` interface AnimationEvent { fromState: string toState: string totalTime: number phaseName: string element: any triggerName: string disabled: boolean } ``` Description ----------- ``` @Component({ host: { '[@myAnimationTrigger]': 'someExpression', '(@myAnimationTrigger.start)': 'captureStartEvent($event)', '(@myAnimationTrigger.done)': 'captureDoneEvent($event)', }, animations: [ trigger("myAnimationTrigger", [ // ... ]) ] }) class MyComponent { someExpression: any = false; captureStartEvent(event: AnimationEvent) { // the toState, fromState and totalTime data is accessible from the event variable } captureDoneEvent(event: AnimationEvent) { // the toState, fromState and totalTime data is accessible from the event variable } } ``` Properties ---------- | Property | Description | | --- | --- | | `fromState: string` | The name of the state from which the animation is triggered. | | `toState: string` | The name of the state in which the animation completes. | | `totalTime: number` | The time it takes the animation to complete, in milliseconds. | | `phaseName: string` | The animation phase in which the callback was invoked, one of "start" or "done". | | `element: any` | The element to which the animation is attached. | | `triggerName: string` | Internal. | | `disabled: boolean` | Internal. | angular AnimateChildOptions AnimateChildOptions =================== `interface` Adds duration options to control animation styling and timing for a child animation. ``` interface AnimateChildOptions extends AnimationOptions { duration?: number | string // inherited from animations/AnimationOptions delay?: number | string params?: {...} } ``` See also -------- * `[animateChild](animatechild)()` Properties ---------- | Property | Description | | --- | --- | | `duration?: number | string` | | angular sequence sequence ======== `function` Defines a list of animation steps to be run sequentially, one by one. ### `sequence(steps: AnimationMetadata[], options: AnimationOptions = null): AnimationSequenceMetadata` ###### Parameters | | | | | --- | --- | --- | | `steps` | `[AnimationMetadata](animationmetadata)[]` | An array of animation step objects.* Steps defined by `<style>()` calls apply the styling data immediately. * Steps defined by `<animate>()` calls apply the styling data over time as specified by the timing data. ``` sequence([ style({ opacity: 0 }), animate("1s", style({ opacity: 1 })) ]) ``` | | `options` | `[AnimationOptions](animationoptions)` | An options object containing a delay and developer-defined parameters that provide styling defaults and can be overridden on invocation. Optional. Default is `null`. | ###### Returns `[AnimationSequenceMetadata](animationsequencemetadata)`: An object that encapsulates the sequence data. Usage notes ----------- When you pass an array of steps to a `<transition>()` call, the steps run sequentially by default. Compare this to the `[group()](group)` call, which runs animation steps in parallel. When a sequence is used within a `[group()](group)` or a `<transition>()` call, execution continues to the next instruction only after each of the inner animation steps have completed. angular AnimationBuilder AnimationBuilder ================ `class` An injectable service that produces an animation sequence programmatically within an Angular component or directive. Provided by the `[BrowserAnimationsModule](../platform-browser/animations/browseranimationsmodule)` or `[NoopAnimationsModule](../platform-browser/animations/noopanimationsmodule)`. ``` abstract class AnimationBuilder { abstract build(animation: AnimationMetadata | AnimationMetadata[]): AnimationFactory } ``` Methods ------- | build() | | --- | | Builds a factory for producing a defined animation. See also:* `<animate>()` | | `abstract build(animation: AnimationMetadata | AnimationMetadata[]): AnimationFactory` Parameters | | | | | --- | --- | --- | | `<animation>` | `[AnimationMetadata](animationmetadata) | [AnimationMetadata](animationmetadata)[]` | A reusable animation definition. | Returns `[AnimationFactory](animationfactory)`: A factory object that can create a player for the defined animation. | Usage notes ----------- To use this service, add it to your component or directive as a dependency. The service is instantiated along with your component. Apps do not typically need to create their own animation players, but if you do need to, follow these steps: 1. Use the `[AnimationBuilder.build](animationbuilder#build)()` method to create a programmatic animation. The method returns an `[AnimationFactory](animationfactory)` instance. 2. Use the factory object to create an `[AnimationPlayer](animationplayer)` and attach it to a DOM element. 3. Use the player object to control the animation programmatically. For example: ``` // import the service from BrowserAnimationsModule import {AnimationBuilder} from '@angular/animations'; // require the service as a dependency class MyCmp { constructor(private _builder: AnimationBuilder) {} makeAnimation(element: any) { // first define a reusable animation const myAnimation = this._builder.build([ style({ width: 0 }), animate(1000, style({ width: '100px' })) ]); // use the returned factory object to create a player const player = myAnimation.create(element); player.play(); } } ``` angular AnimationAnimateRefMetadata AnimationAnimateRefMetadata =========================== `interface` Encapsulates a reusable animation. Instantiated and returned by the `[useAnimation](useanimation)()` function. ``` interface AnimationAnimateRefMetadata extends AnimationMetadata { animation: AnimationReferenceMetadata options: AnimationOptions | null // inherited from animations/AnimationMetadata type: AnimationMetadataType } ``` Properties ---------- | Property | Description | | --- | --- | | `<animation>: [AnimationReferenceMetadata](animationreferencemetadata)` | An animation reference object. | | `options: [AnimationOptions](animationoptions) | null` | An options object containing a delay and developer-defined parameters that provide styling defaults and can be overridden on invocation. Default delay is 0. | angular group group ===== `function` Defines a list of animation steps to be run in parallel. ### `group(steps: AnimationMetadata[], options: AnimationOptions = null): AnimationGroupMetadata` ###### Parameters | | | | | --- | --- | --- | | `steps` | `[AnimationMetadata](animationmetadata)[]` | An array of animation step objects.* When steps are defined by `<style>()` or `<animate>()` function calls, each call within the group is executed instantly. * To specify offset styles to be applied at a later time, define steps with `<keyframes>()`, or use `<animate>()` calls with a delay value. For example: ``` group([ animate("1s", style({ background: "black" })), animate("2s", style({ color: "white" })) ]) ``` | | `options` | `[AnimationOptions](animationoptions)` | An options object containing a delay and developer-defined parameters that provide styling defaults and can be overridden on invocation. Optional. Default is `null`. | ###### Returns `[AnimationGroupMetadata](animationgroupmetadata)`: An object that encapsulates the group data. Usage notes ----------- Grouped animations are useful when a series of styles must be animated at different starting times and closed off at different ending times. When called within a `<sequence>()` or a `<transition>()` call, does not continue to the next instruction until all of the inner animation steps have completed. angular AnimationKeyframesSequenceMetadata AnimationKeyframesSequenceMetadata ================================== `interface` Encapsulates a keyframes sequence. Instantiated and returned by the `<keyframes>()` function. ``` interface AnimationKeyframesSequenceMetadata extends AnimationMetadata { steps: AnimationStyleMetadata[] // inherited from animations/AnimationMetadata type: AnimationMetadataType } ``` Properties ---------- | Property | Description | | --- | --- | | `steps: [AnimationStyleMetadata](animationstylemetadata)[]` | An array of animation styles. | angular useAnimation useAnimation ============ `function` Starts a reusable animation that is created using the `<animation>()` function. ### `useAnimation(animation: AnimationReferenceMetadata, options: AnimationOptions = null): AnimationAnimateRefMetadata` ###### Parameters | | | | | --- | --- | --- | | `<animation>` | `[AnimationReferenceMetadata](animationreferencemetadata)` | The reusable animation to start. | | `options` | `[AnimationOptions](animationoptions)` | An options object that can contain a delay value for the start of the animation, and additional override values for developer-defined parameters. Optional. Default is `null`. | ###### Returns `[AnimationAnimateRefMetadata](animationanimaterefmetadata)`: An object that contains the animation parameters. angular stagger stagger ======= `function` Use within an animation `<query>()` call to issue a timing gap after each queried item is animated. ### `stagger(timings: string | number, animation: AnimationMetadata | AnimationMetadata[]): AnimationStaggerMetadata` ###### Parameters | | | | | --- | --- | --- | | `timings` | `string | number` | A delay value. | | `<animation>` | `[AnimationMetadata](animationmetadata) | [AnimationMetadata](animationmetadata)[]` | One ore more animation steps. | ###### Returns `[AnimationStaggerMetadata](animationstaggermetadata)`: An object that encapsulates the stagger data. Usage notes ----------- In the following example, a container element wraps a list of items stamped out by an `[ngFor](../common/ngfor)`. The container element contains an animation trigger that will later be set to query for each of the inner items. Each time items are added, the opacity fade-in animation runs, and each removed item is faded out. When either of these animations occur, the stagger effect is applied after each item's animation is started. ``` <!-- list.component.html --> <button (click)="toggle()">Show / Hide Items</button> <hr /> <div [@listAnimation]="items.length"> <div *ngFor="let item of items"> {{ item }} </div> </div> ``` Here is the component code: ``` import {trigger, transition, style, animate, query, stagger} from '@angular/animations'; @Component({ templateUrl: 'list.component.html', animations: [ trigger('listAnimation', [ ... ]) ] }) class ListComponent { items = []; showItems() { this.items = [0,1,2,3,4]; } hideItems() { this.items = []; } toggle() { this.items.length ? this.hideItems() : this.showItems(); } } ``` Here is the animation trigger code: ``` trigger('listAnimation', [ transition('* => *', [ // each time the binding value changes query(':leave', [ stagger(100, [ animate('0.5s', style({ opacity: 0 })) ]) ]), query(':enter', [ style({ opacity: 0 }), stagger(100, [ animate('0.5s', style({ opacity: 1 })) ]) ]) ]) ]) ```
programming_docs
angular AnimationAnimateMetadata AnimationAnimateMetadata ======================== `interface` Encapsulates an animation step. Instantiated and returned by the `<animate>()` function. ``` interface AnimationAnimateMetadata extends AnimationMetadata { timings: string | number | AnimateTimings styles: AnimationStyleMetadata | AnimationKeyframesSequenceMetadata | null // inherited from animations/AnimationMetadata type: AnimationMetadataType } ``` Properties ---------- | Property | Description | | --- | --- | | `timings: string | number | [AnimateTimings](animatetimings)` | The timing data for the step. | | `styles: [AnimationStyleMetadata](animationstylemetadata) | [AnimationKeyframesSequenceMetadata](animationkeyframessequencemetadata) | null` | A set of styles used in the step. | angular AnimationTransitionMetadata AnimationTransitionMetadata =========================== `interface` Encapsulates an animation transition. Instantiated and returned by the `<transition>()` function. ``` interface AnimationTransitionMetadata extends AnimationMetadata { expr: string | ((fromState: string, toState: string, element?: any, params?: {...})) animation: AnimationMetadata | AnimationMetadata[] options: AnimationOptions | null // inherited from animations/AnimationMetadata type: AnimationMetadataType } ``` Properties ---------- | Property | Description | | --- | --- | | `expr: string | ((fromState: string, toState: string, element?: any, params?: { [key: string]: any; }) => boolean)` | An expression that describes a state change. | | `<animation>: [AnimationMetadata](animationmetadata) | [AnimationMetadata](animationmetadata)[]` | One or more animation objects to which this transition applies. | | `options: [AnimationOptions](animationoptions) | null` | An options object containing a delay and developer-defined parameters that provide styling defaults and can be overridden on invocation. Default delay is 0. | angular AnimationFactory AnimationFactory ================ `class` A factory object returned from the `[AnimationBuilder.build](animationbuilder#build)()` method. ``` abstract class AnimationFactory { abstract create(element: any, options?: AnimationOptions): AnimationPlayer } ``` Methods ------- | create() | | --- | | Creates an `[AnimationPlayer](animationplayer)` instance for the reusable animation defined by the `[AnimationBuilder.build](animationbuilder#build)()` method that created this factory and attaches the new player a DOM element. | | `abstract create(element: any, options?: AnimationOptions): AnimationPlayer` Parameters | | | | | --- | --- | --- | | `element` | `any` | The DOM element to which to attach the player. | | `options` | `[AnimationOptions](animationoptions)` | A set of options that can include a time delay and additional developer-defined parameters. Optional. Default is `undefined`. | Returns `[AnimationPlayer](animationplayer)` | angular AnimationAnimateChildMetadata AnimationAnimateChildMetadata ============================= `interface` Encapsulates a child animation, that can be run explicitly when the parent is run. Instantiated and returned by the `[animateChild](animatechild)` function. ``` interface AnimationAnimateChildMetadata extends AnimationMetadata { options: AnimationOptions | null // inherited from animations/AnimationMetadata type: AnimationMetadataType } ``` Properties ---------- | Property | Description | | --- | --- | | `options: [AnimationOptions](animationoptions) | null` | An options object containing a delay and developer-defined parameters that provide styling defaults and can be overridden on invocation. Default delay is 0. | angular animation animation ========= `function` Produces a reusable animation that can be invoked in another animation or sequence, by calling the `[useAnimation](useanimation)()` function. ### `animation(steps: AnimationMetadata | AnimationMetadata[], options: AnimationOptions = null): AnimationReferenceMetadata` ###### Parameters | | | | | --- | --- | --- | | `steps` | `[AnimationMetadata](animationmetadata) | [AnimationMetadata](animationmetadata)[]` | One or more animation objects, as returned by the `<animate>()` or `<sequence>()` function, that form a transformation from one state to another. A sequence is used by default when you pass an array. | | `options` | `[AnimationOptions](animationoptions)` | An options object that can contain a delay value for the start of the animation, and additional developer-defined parameters. Provided values for additional parameters are used as defaults, and override values can be passed to the caller on invocation. Optional. Default is `null`. | ###### Returns `[AnimationReferenceMetadata](animationreferencemetadata)`: An object that encapsulates the animation data. Usage notes ----------- The following example defines a reusable animation, providing some default parameter values. ``` var fadeAnimation = animation([ style({ opacity: '{{ start }}' }), animate('{{ time }}', style({ opacity: '{{ end }}'})) ], { params: { time: '1000ms', start: 0, end: 1 }}); ``` The following invokes the defined animation with a call to `[useAnimation](useanimation)()`, passing in override parameter values. ``` useAnimation(fadeAnimation, { params: { time: '2s', start: 1, end: 0 } }) ``` If any of the passed-in parameter values are missing from this call, the default values are used. If one or more parameter values are missing before a step is animated, `[useAnimation](useanimation)()` throws an error. angular AnimationStaggerMetadata AnimationStaggerMetadata ======================== `interface` Encapsulates parameters for staggering the start times of a set of animation steps. Instantiated and returned by the `<stagger>()` function. ``` interface AnimationStaggerMetadata extends AnimationMetadata { timings: string | number animation: AnimationMetadata | AnimationMetadata[] // inherited from animations/AnimationMetadata type: AnimationMetadataType } ``` Properties ---------- | Property | Description | | --- | --- | | `timings: string | number` | The timing data for the steps. | | `<animation>: [AnimationMetadata](animationmetadata) | [AnimationMetadata](animationmetadata)[]` | One or more animation steps. | angular animateChild animateChild ============ `function` Executes a queried inner animation element within an animation sequence. ### `animateChild(options: AnimateChildOptions = null): AnimationAnimateChildMetadata` ###### Parameters | | | | | --- | --- | --- | | `options` | `[AnimateChildOptions](animatechildoptions)` | An options object that can contain a delay value for the start of the animation, and additional override values for developer-defined parameters. Optional. Default is `null`. | ###### Returns `[AnimationAnimateChildMetadata](animationanimatechildmetadata)`: An object that encapsulates the child animation data. Usage notes ----------- Each time an animation is triggered in Angular, the parent animation has priority and any child animations are blocked. In order for a child animation to run, the parent animation must query each of the elements containing child animations, and run them using this function. Note that this feature is designed to be used with `<query>()` and it will only work with animations that are assigned using the Angular animation library. CSS keyframes and transitions are not handled by this API. angular AnimationSequenceMetadata AnimationSequenceMetadata ========================= `interface` Encapsulates an animation sequence. Instantiated and returned by the `<sequence>()` function. ``` interface AnimationSequenceMetadata extends AnimationMetadata { steps: AnimationMetadata[] options: AnimationOptions | null // inherited from animations/AnimationMetadata type: AnimationMetadataType } ``` Properties ---------- | Property | Description | | --- | --- | | `steps: [AnimationMetadata](animationmetadata)[]` | An array of animation step objects. | | `options: [AnimationOptions](animationoptions) | null` | An options object containing a delay and developer-defined parameters that provide styling defaults and can be overridden on invocation. Default delay is 0. | angular AnimationMetadataType AnimationMetadataType ===================== `enum` Constants for the categories of parameters that can be defined for animations. [See more...](animationmetadatatype#description) ``` enum AnimationMetadataType { State: 0 Transition: 1 Sequence: 2 Group: 3 Animate: 4 Keyframes: 5 Style: 6 Trigger: 7 Reference: 8 AnimateChild: 9 AnimateRef: 10 Query: 11 Stagger: 12 } ``` Description ----------- A corresponding function defines a set of parameters for each category, and collects them into a corresponding `[AnimationMetadata](animationmetadata)` object. Members ------- | Member | Description | | --- | --- | | `State: 0` | Associates a named animation state with a set of CSS styles. See [`state()`](state) | | `Transition: 1` | Data for a transition from one animation state to another. See `<transition>()` | | `Sequence: 2` | Contains a set of animation steps. See `<sequence>()` | | `Group: 3` | Contains a set of animation steps. See `[group()](group)` | | `Animate: 4` | Contains an animation step. See `<animate>()` | | `Keyframes: 5` | Contains a set of animation steps. See `<keyframes>()` | | `Style: 6` | Contains a set of CSS property-value pairs into a named style. See `<style>()` | | `Trigger: 7` | Associates an animation with an entry trigger that can be attached to an element. See `<trigger>()` | | `Reference: 8` | Contains a re-usable animation. See `<animation>()` | | `AnimateChild: 9` | Contains data to use in executing child animations returned by a query. See `[animateChild](animatechild)()` | | `AnimateRef: 10` | Contains animation parameters for a re-usable animation. See `[useAnimation](useanimation)()` | | `[Query](../core/query): 11` | Contains child-animation query data. See `<query>()` | | `Stagger: 12` | Contains data for staggering an animation sequence. See `<stagger>()` | angular style style ===== `function` Declares a key/value object containing CSS properties/styles that can then be used for an animation [`state`](state), within an animation `<sequence>`, or as styling data for calls to `<animate>()` and `<keyframes>()`. ### `style(tokens: "*" | { [key: string]: string | number; } | ("*" | { [key: string]: string | number; })[]): AnimationStyleMetadata` ###### Parameters | | | | | --- | --- | --- | | `tokens` | `"*" | { [key: string]: string | number; } | ("*" | { [key: string]: string | number; })[]` | A set of CSS styles or HTML styles associated with an animation state. The value can be any of the following:* A key-value style pair associating a CSS property with a value. * An array of key-value style pairs. * An asterisk (\*), to use auto-styling, where styles are derived from the element being animated and applied to the animation when it starts. Auto-styling can be used to define a state that depends on layout or other environmental factors. | ###### Returns `[AnimationStyleMetadata](animationstylemetadata)`: An object that encapsulates the style data. Usage notes ----------- The following examples create animation styles that collect a set of CSS property values: ``` // string values for CSS properties style({ background: "red", color: "blue" }) // numerical pixel values style({ width: 100, height: 0 }) ``` The following example uses auto-styling to allow an element to animate from a height of 0 up to its full height: ``` style({ height: 0 }), animate("1s", style({ height: "*" })) ``` angular keyframes keyframes ========= `function` Defines a set of animation styles, associating each style with an optional `offset` value. ### `keyframes(steps: AnimationStyleMetadata[]): AnimationKeyframesSequenceMetadata` ###### Parameters | | | | | --- | --- | --- | | `steps` | `[AnimationStyleMetadata](animationstylemetadata)[]` | A set of animation styles with optional offset data. The optional `offset` value for a style specifies a percentage of the total animation time at which that style is applied. | ###### Returns `[AnimationKeyframesSequenceMetadata](animationkeyframessequencemetadata)`: An object that encapsulates the keyframes data. Usage notes ----------- Use with the `<animate>()` call. Instead of applying animations from the current state to the destination state, keyframes describe how each style entry is applied and at what point within the animation arc. Compare [CSS Keyframe Animations](https://www.w3schools.com/css/css3_animations.asp). ### Usage In the following example, the offset values describe when each `backgroundColor` value is applied. The color is red at the start, and changes to blue when 20% of the total time has elapsed. ``` // the provided offset values animate("5s", keyframes([ style({ backgroundColor: "red", offset: 0 }), style({ backgroundColor: "blue", offset: 0.2 }), style({ backgroundColor: "orange", offset: 0.3 }), style({ backgroundColor: "black", offset: 1 }) ])) ``` If there are no `offset` values specified in the style entries, the offsets are calculated automatically. ``` animate("5s", keyframes([ style({ backgroundColor: "red" }) // offset = 0 style({ backgroundColor: "blue" }) // offset = 0.33 style({ backgroundColor: "orange" }) // offset = 0.66 style({ backgroundColor: "black" }) // offset = 1 ])) ``` angular AnimationPlayer AnimationPlayer =============== `interface` Provides programmatic control of a reusable animation sequence, built using the `[AnimationBuilder.build](animationbuilder#build)()` method which returns an `[AnimationFactory](animationfactory)`, whose `[create](animationfactory#create)()` method instantiates and initializes this interface. ``` interface AnimationPlayer { parentPlayer: AnimationPlayer | null totalTime: number beforeDestroy?: () => any onDone(fn: () => void): void onStart(fn: () => void): void onDestroy(fn: () => void): void init(): void hasStarted(): boolean play(): void pause(): void restart(): void finish(): void destroy(): void reset(): void setPosition(position: any): void getPosition(): number } ``` Class implementations --------------------- * `[NoopAnimationPlayer](noopanimationplayer)` + `[MockAnimationPlayer](browser/testing/mockanimationplayer)` See also -------- * `[AnimationBuilder](animationbuilder)` * `[AnimationFactory](animationfactory)` * `<animate>()` Properties ---------- | Property | Description | | --- | --- | | `parentPlayer: [AnimationPlayer](animationplayer) | null` | The parent of this player, if any. | | `totalTime: number` | Read-Only The total run time of the animation, in milliseconds. | | `beforeDestroy?: () => any` | Provides a callback to invoke before the animation is destroyed. | Methods ------- | onDone() | | --- | | Provides a callback to invoke when the animation finishes. See also:* `finish()` | | `onDone(fn: () => void): void` Parameters | | | | | --- | --- | --- | | `fn` | `() => void` | The callback function. | Returns `void` | | onStart() | | --- | | Provides a callback to invoke when the animation starts. See also:* `run()` | | `onStart(fn: () => void): void` Parameters | | | | | --- | --- | --- | | `fn` | `() => void` | The callback function. | Returns `void` | | onDestroy() | | --- | | Provides a callback to invoke after the animation is destroyed. See also:* `destroy()` * `beforeDestroy()` | | `onDestroy(fn: () => void): void` Parameters | | | | | --- | --- | --- | | `fn` | `() => void` | The callback function. | Returns `void` | | init() | | --- | | Initializes the animation. | | `init(): void` Parameters There are no parameters. Returns `void` | | hasStarted() | | --- | | Reports whether the animation has started. | | `hasStarted(): boolean` Parameters There are no parameters. Returns `boolean`: True if the animation has started, false otherwise. | | play() | | --- | | Runs the animation, invoking the `onStart()` callback. | | `play(): void` Parameters There are no parameters. Returns `void` | | pause() | | --- | | Pauses the animation. | | `pause(): void` Parameters There are no parameters. Returns `void` | | restart() | | --- | | Restarts the paused animation. | | `restart(): void` Parameters There are no parameters. Returns `void` | | finish() | | --- | | Ends the animation, invoking the `onDone()` callback. | | `finish(): void` Parameters There are no parameters. Returns `void` | | destroy() | | --- | | Destroys the animation, after invoking the `beforeDestroy()` callback. Calls the `onDestroy()` callback when destruction is completed. | | `destroy(): void` Parameters There are no parameters. Returns `void` | | reset() | | --- | | Resets the animation to its initial state. | | `reset(): void` Parameters There are no parameters. Returns `void` | | setPosition() | | --- | | Sets the position of the animation. | | `setPosition(position: any): void` Parameters | | | | | --- | --- | --- | | `position` | `any` | A 0-based offset into the duration, in milliseconds. | Returns `void` | | getPosition() | | --- | | Reports the current position of the animation. | | `getPosition(): number` Parameters There are no parameters. Returns `number`: A 0-based offset into the duration, in milliseconds. | angular AnimationTriggerMetadata AnimationTriggerMetadata ======================== `interface` Contains an animation trigger. Instantiated and returned by the `<trigger>()` function. ``` interface AnimationTriggerMetadata extends AnimationMetadata { name: string definitions: AnimationMetadata[] options: {...} // inherited from animations/AnimationMetadata type: AnimationMetadataType } ``` Properties ---------- | Property | Description | | --- | --- | | `name: string` | The trigger name, used to associate it with an element. Unique within the component. | | `definitions: [AnimationMetadata](animationmetadata)[]` | An animation definition object, containing an array of state and transition declarations. | | `options: { params?: { [name: string]: any; }; } | null` | An options object containing a delay and developer-defined parameters that provide styling defaults and can be overridden on invocation. Default delay is 0. | angular query query ===== `function` Finds one or more inner elements within the current element that is being animated within a sequence. Use with `<animate>()`. ### `query(selector: string, animation: AnimationMetadata | AnimationMetadata[], options: AnimationQueryOptions = null): AnimationQueryMetadata` ###### Parameters | | | | | --- | --- | --- | | `selector` | `string` | The element to query, or a set of elements that contain Angular-specific characteristics, specified with one or more of the following tokens.* `<query>(":enter")` or `<query>(":leave")` : Query for newly inserted/removed elements (not all elements can be queried via these tokens, see [Entering and Leaving Elements](query#entering-and-leaving-elements)) * `<query>(":animating")` : Query all currently animating elements. * `<query>("@triggerName")` : Query elements that contain an animation trigger. * `<query>("@*")` : Query all elements that contain an animation triggers. * `<query>(":self")` : Include the current element into the animation sequence. | | `<animation>` | `[AnimationMetadata](animationmetadata) | [AnimationMetadata](animationmetadata)[]` | One or more animation steps to apply to the queried element or elements. An array is treated as an animation sequence. | | `options` | `[AnimationQueryOptions](animationqueryoptions)` | An options object. Use the 'limit' field to limit the total number of items to collect. Optional. Default is `null`. | ###### Returns `[AnimationQueryMetadata](animationquerymetadata)`: An object that encapsulates the query data. Usage notes ----------- ### Multiple Tokens Tokens can be merged into a combined query selector string. For example: ``` query(':self, .record:enter, .record:leave, @subTrigger', [...]) ``` The `<query>()` function collects multiple elements and works internally by using `element.querySelectorAll`. Use the `limit` field of an options object to limit the total number of items to be collected. For example: ``` query('div', [ animate(...), animate(...) ], { limit: 1 }) ``` By default, throws an error when zero items are found. Set the `optional` flag to ignore this error. For example: ``` query('.some-element-that-may-not-be-there', [ animate(...), animate(...) ], { optional: true }) ``` ### Entering and Leaving Elements Not all elements can be queried via the `:enter` and `:leave` tokens, the only ones that can are those that Angular assumes can enter/leave based on their own logic (if their insertion/removal is simply a consequence of that of their parent they should be queried via a different token in their parent's `:enter`/`:leave` transitions). The only elements Angular assumes can enter/leave based on their own logic (thus the only ones that can be queried via the `:enter` and `:leave` tokens) are: * Those inserted dynamically (via `[ViewContainerRef](../core/viewcontainerref)`) * Those that have a structural directive (which, under the hood, are a subset of the above ones) > Note that elements will be successfully queried via `:enter`/`:leave` even if their insertion/removal is not done manually via `[ViewContainerRef](../core/viewcontainerref)`or caused by their structural directive (e.g. they enter/exit alongside their parent). > > > There is an exception to what previously mentioned, besides elements entering/leaving based on their own logic, elements with an animation trigger can always be queried via `:leave` when their parent is also leaving. > > ### Usage Example The following example queries for inner elements and animates them individually using `<animate>()`. ``` @Component({ selector: 'inner', template: ` <div [@queryAnimation]="exp"> <h1>Title</h1> <div class="content"> Blah blah blah </div> </div> `, animations: [ trigger('queryAnimation', [ transition('* => goAnimate', [ // hide the inner elements query('h1', style({ opacity: 0 })), query('.content', style({ opacity: 0 })), // animate the inner elements in, one by one query('h1', animate(1000, style({ opacity: 1 }))), query('.content', animate(1000, style({ opacity: 1 }))), ]) ]) ] }) class Cmp { exp = ''; goAnimate() { this.exp = 'goAnimate'; } } ```
programming_docs
angular trigger trigger ======= `function` Creates a named animation trigger, containing a list of [`state()`](state) and `<transition>()` entries to be evaluated when the expression bound to the trigger changes. ### `trigger(name: string, definitions: AnimationMetadata[]): AnimationTriggerMetadata` ###### Parameters | | | | | --- | --- | --- | | `name` | `string` | An identifying string. | | `definitions` | `[AnimationMetadata](animationmetadata)[]` | An animation definition object, containing an array of [`state()`](state) and `<transition>()` declarations. | ###### Returns `[AnimationTriggerMetadata](animationtriggermetadata)`: An object that encapsulates the trigger data. Usage notes ----------- Define an animation trigger in the `animations` section of `@[Component](../core/component)` metadata. In the template, reference the trigger by name and bind it to a trigger expression that evaluates to a defined animation state, using the following format: `[@triggerName]="expression"` Animation trigger bindings convert all values to strings, and then match the previous and current values against any linked transitions. Booleans can be specified as `1` or `true` and `0` or `false`. ### Usage Example The following example creates an animation trigger reference based on the provided name value. The provided animation value is expected to be an array consisting of state and transition declarations. ``` @Component({ selector: "my-component", templateUrl: "my-component-tpl.html", animations: [ trigger("myAnimationTrigger", [ state(...), state(...), transition(...), transition(...) ]) ] }) class MyComponent { myStatusExp = "something"; } ``` The template associated with this component makes use of the defined trigger by binding to an element within its template code. ``` <!-- somewhere inside of my-component-tpl.html --> <div [@myAnimationTrigger]="myStatusExp">...</div> ``` ### Using an inline function The `<transition>` animation method also supports reading an inline function which can decide if its associated animation should be run. ``` // this method is run each time the `myAnimationTrigger` trigger value changes. function myInlineMatcherFn(fromState: string, toState: string, element: any, params: {[key: string]: any}): boolean { // notice that `element` and `params` are also available here return toState == 'yes-please-animate'; } @Component({ selector: 'my-component', templateUrl: 'my-component-tpl.html', animations: [ trigger('myAnimationTrigger', [ transition(myInlineMatcherFn, [ // the animation sequence code ]), ]) ] }) class MyComponent { myStatusExp = "yes-please-animate"; } ``` ### Disabling Animations When true, the special animation control binding `@.disabled` binding prevents all animations from rendering. Place the `@.disabled` binding on an element to disable animations on the element itself, as well as any inner animation triggers within the element. The following example shows how to use this feature: ``` @Component({ selector: 'my-component', template: ` <div [@.disabled]="isDisabled"> <div [@childAnimation]="exp"></div> </div> `, animations: [ trigger("childAnimation", [ // ... ]) ] }) class MyComponent { isDisabled = true; exp = '...'; } ``` When `@.disabled` is true, it prevents the `@childAnimation` trigger from animating, along with any inner animations. ### Disable animations application-wide When an area of the template is set to have animations disabled, **all** inner components have their animations disabled as well. This means that you can disable all animations for an app by placing a host binding set on `@.disabled` on the topmost Angular component. ``` import {Component, HostBinding} from '@angular/core'; @Component({ selector: 'app-component', templateUrl: 'app.component.html', }) class AppComponent { @HostBinding('@.disabled') public animationsDisabled = true; } ``` ### Overriding disablement of inner animations Despite inner animations being disabled, a parent animation can `<query>()` for inner elements located in disabled areas of the template and still animate them if needed. This is also the case for when a sub animation is queried by a parent and then later animated using `[animateChild](animatechild)()`. ### Detecting when an animation is disabled If a region of the DOM (or the entire application) has its animations disabled, the animation trigger callbacks still fire, but for zero seconds. When the callback fires, it provides an instance of an `[AnimationEvent](animationevent)`. If animations are disabled, the `.disabled` flag on the event is true. angular AnimationMetadata AnimationMetadata ================= `interface` Base for animation data structures. ``` interface AnimationMetadata { type: AnimationMetadataType } ``` Child interfaces ---------------- * `[AnimationAnimateChildMetadata](animationanimatechildmetadata)` * `[AnimationAnimateMetadata](animationanimatemetadata)` * `[AnimationAnimateRefMetadata](animationanimaterefmetadata)` * `[AnimationGroupMetadata](animationgroupmetadata)` * `[AnimationKeyframesSequenceMetadata](animationkeyframessequencemetadata)` * `[AnimationQueryMetadata](animationquerymetadata)` * `[AnimationReferenceMetadata](animationreferencemetadata)` * `[AnimationSequenceMetadata](animationsequencemetadata)` * `[AnimationStaggerMetadata](animationstaggermetadata)` * `[AnimationStateMetadata](animationstatemetadata)` * `[AnimationStyleMetadata](animationstylemetadata)` * `[AnimationTransitionMetadata](animationtransitionmetadata)` * `[AnimationTriggerMetadata](animationtriggermetadata)` Properties ---------- | Property | Description | | --- | --- | | `type: [AnimationMetadataType](animationmetadatatype)` | | angular AnimationQueryMetadata AnimationQueryMetadata ====================== `interface` Encapsulates an animation query. Instantiated and returned by the `<query>()` function. ``` interface AnimationQueryMetadata extends AnimationMetadata { selector: string animation: AnimationMetadata | AnimationMetadata[] options: AnimationQueryOptions | null // inherited from animations/AnimationMetadata type: AnimationMetadataType } ``` Properties ---------- | Property | Description | | --- | --- | | `selector: string` | The CSS selector for this query. | | `<animation>: [AnimationMetadata](animationmetadata) | [AnimationMetadata](animationmetadata)[]` | One or more animation step objects. | | `options: [AnimationQueryOptions](animationqueryoptions) | null` | A query options object. | angular AnimateTimings AnimateTimings ============== `type-alias` Represents animation-step timing parameters for an animation step. ``` type AnimateTimings = { duration: number; delay: number; easing: string | null; }; ``` See also -------- * `<animate>()` angular AnimationOptions AnimationOptions ================ `interface` Options that control animation styling and timing. [See more...](animationoptions#description) ``` interface AnimationOptions { delay?: number | string params?: {...} } ``` Child interfaces ---------------- * `[AnimateChildOptions](animatechildoptions)` * `[AnimationQueryOptions](animationqueryoptions)` Description ----------- The following animation functions accept `[AnimationOptions](animationoptions)` data: * `<transition>()` * `<sequence>()` * `[group()](group)` * `<query>()` * `<animation>()` * `[useAnimation](useanimation)()` * `[animateChild](animatechild)()` Programmatic animations built using the `[AnimationBuilder](animationbuilder)` service also make use of `[AnimationOptions](animationoptions)`. Properties ---------- | Property | Description | | --- | --- | | `delay?: number | string` | Sets a time-delay for initiating an animation action. A number and optional time unit, such as "1s" or "10ms" for one second and 10 milliseconds, respectively.The default unit is milliseconds. Default value is 0, meaning no delay. | | `params?: { [name: string]: any; }` | A set of developer-defined parameters that modify styling and timing when an animation action starts. An array of key-value pairs, where the provided value is used as a default. | angular animate animate ======= `function` Defines an animation step that combines styling information with timing information. ### `animate(timings: string | number, styles: AnimationStyleMetadata | AnimationKeyframesSequenceMetadata = null): AnimationAnimateMetadata` ###### Parameters | | | | | --- | --- | --- | | `timings` | `string | number` | Sets `[AnimateTimings](animatetimings)` for the parent animation. A string in the format "duration [delay][easing]".* Duration and delay are expressed as a number and optional time unit, such as "1s" or "10ms" for one second and 10 milliseconds, respectively. The default unit is milliseconds. * The easing value controls how the animation accelerates and decelerates during its runtime. Value is one of `ease`, `ease-in`, `ease-out`, `ease-in-out`, or a `cubic-bezier()` function call. If not supplied, no easing is applied. For example, the string "1s 100ms ease-out" specifies a duration of 1000 milliseconds, and delay of 100 ms, and the "ease-out" easing style, which decelerates near the end of the duration. | | `styles` | `[AnimationStyleMetadata](animationstylemetadata) | [AnimationKeyframesSequenceMetadata](animationkeyframessequencemetadata)` | Sets AnimationStyles for the parent animation. A function call to either `<style>()` or `<keyframes>()` that returns a collection of CSS style entries to be applied to the parent animation. When null, uses the styles from the destination state. This is useful when describing an animation step that will complete an animation; see "Animating to the final state" in `transitions()`. Optional. Default is `null`. | ###### Returns `[AnimationAnimateMetadata](animationanimatemetadata)`: An object that encapsulates the animation step. Usage notes ----------- Call within an animation `<sequence>()`, `[group()](group)`, or `<transition>()` call to specify an animation step that applies given style data to the parent animation for a given amount of time. ### Syntax Examples **Timing examples** The following examples show various `timings` specifications. * `<animate>(500)` : Duration is 500 milliseconds. * `<animate>("1s")` : Duration is 1000 milliseconds. * `<animate>("100ms 0.5s")` : Duration is 100 milliseconds, delay is 500 milliseconds. * `<animate>("5s ease-in")` : Duration is 5000 milliseconds, easing in. * `<animate>("5s 10ms cubic-bezier(.17,.67,.88,.1)")` : Duration is 5000 milliseconds, delay is 10 milliseconds, easing according to a bezier curve. **Style examples** The following example calls `<style>()` to set a single CSS style. ``` animate(500, style({ background: "red" })) ``` The following example calls `<keyframes>()` to set a CSS style to different values for successive keyframes. ``` animate(500, keyframes( [ style({ background: "blue" }), style({ background: "red" }) ]) ``` angular state state ===== `function` Declares an animation state within a trigger attached to an element. ### `state(name: string, styles: AnimationStyleMetadata, options?: { params: { [name: string]: any; }; }): AnimationStateMetadata` ###### Parameters | | | | | --- | --- | --- | | `name` | `string` | One or more names for the defined state in a comma-separated string. The following reserved state names can be supplied to define a style for specific use cases:* `void` You can associate styles with this name to be used when the element is detached from the application. For example, when an `[ngIf](../common/ngif)` evaluates to false, the state of the associated element is void. * `*` (asterisk) Indicates the default state. You can associate styles with this name to be used as the fallback when the state that is being animated is not declared within the trigger. | | `styles` | `[AnimationStyleMetadata](animationstylemetadata)` | A set of CSS styles associated with this state, created using the `<style>()` function. This set of styles persists on the element once the state has been reached. | | `options` | `object` | Parameters that can be passed to the state when it is invoked. 0 or more key-value pairs. Optional. Default is `undefined`. | ###### Returns `[AnimationStateMetadata](animationstatemetadata)`: An object that encapsulates the new state data. Usage notes ----------- Use the `<trigger>()` function to register states to an animation trigger. Use the `<transition>()` function to animate between states. When a state is active within a component, its associated styles persist on the element, even when the animation ends. angular AUTO_STYLE AUTO\_STYLE =========== `const` Specifies automatic styling. ### `const AUTO_STYLE: "*";` angular AnimationGroupMetadata AnimationGroupMetadata ====================== `interface` Encapsulates an animation group. Instantiated and returned by the `[group()](group)` function. ``` interface AnimationGroupMetadata extends AnimationMetadata { steps: AnimationMetadata[] options: AnimationOptions | null // inherited from animations/AnimationMetadata type: AnimationMetadataType } ``` Properties ---------- | Property | Description | | --- | --- | | `steps: [AnimationMetadata](animationmetadata)[]` | One or more animation or style steps that form this group. | | `options: [AnimationOptions](animationoptions) | null` | An options object containing a delay and developer-defined parameters that provide styling defaults and can be overridden on invocation. Default delay is 0. | angular AnimationStyleMetadata AnimationStyleMetadata ====================== `interface` Encapsulates an animation style. Instantiated and returned by the `<style>()` function. ``` interface AnimationStyleMetadata extends AnimationMetadata { styles: '*' | {...} offset: number | null // inherited from animations/AnimationMetadata type: AnimationMetadataType } ``` Properties ---------- | Property | Description | | --- | --- | | `styles: '*' | { [key: string]: string | number; } | Array<{ [key: string]: string | number; } | '*'>` | A set of CSS style properties. | | `offset: number | null` | A percentage of the total animate time at which the style is to be applied. | angular AnimationReferenceMetadata AnimationReferenceMetadata ========================== `interface` Encapsulates a reusable animation, which is a collection of individual animation steps. Instantiated and returned by the `<animation>()` function, and passed to the `[useAnimation](useanimation)()` function. ``` interface AnimationReferenceMetadata extends AnimationMetadata { animation: AnimationMetadata | AnimationMetadata[] options: AnimationOptions | null // inherited from animations/AnimationMetadata type: AnimationMetadataType } ``` Properties ---------- | Property | Description | | --- | --- | | `<animation>: [AnimationMetadata](animationmetadata) | [AnimationMetadata](animationmetadata)[]` | One or more animation step objects. | | `options: [AnimationOptions](animationoptions) | null` | An options object containing a delay and developer-defined parameters that provide styling defaults and can be overridden on invocation. Default delay is 0. | angular AnimationDriver AnimationDriver =============== `class` ``` abstract class AnimationDriver { static NOOP: AnimationDriver abstract validateAnimatableStyleProperty?: (prop: string) => boolean abstract validateStyleProperty(prop: string): boolean abstract matchesElement(element: any, selector: string): boolean abstract containsElement(elm1: any, elm2: any): boolean abstract getParentElement(element: unknown): unknown abstract query(element: any, selector: string, multi: boolean): any[] abstract computeStyle(element: any, prop: string, defaultValue?: string): string abstract animate(element: any, keyframes: Map<string, string | number>[], duration: number, delay: number, easing?: string, previousPlayers?: any[], scrubberAccessRequested?: boolean): any } ``` Subclasses ---------- * `[MockAnimationDriver](testing/mockanimationdriver)` Static properties ----------------- | Property | Description | | --- | --- | | `[static](../../upgrade/static) NOOP: [AnimationDriver](animationdriver)` | | Properties ---------- | Property | Description | | --- | --- | | `abstract validateAnimatableStyleProperty?: (prop: string) => boolean` | | Methods ------- | validateStyleProperty() | | --- | | `abstract validateStyleProperty(prop: string): boolean` Parameters | | | | | --- | --- | --- | | `prop` | `string` | | Returns `boolean` | | matchesElement() | | --- | | `abstract matchesElement(element: any, selector: string): boolean` **Deprecated** No longer in use. Will be removed. Parameters | | | | | --- | --- | --- | | `element` | `any` | | | `selector` | `string` | | Returns `boolean` | | containsElement() | | --- | | `abstract containsElement(elm1: any, elm2: any): boolean` Parameters | | | | | --- | --- | --- | | `elm1` | `any` | | | `elm2` | `any` | | Returns `boolean` | | getParentElement() | | --- | | Obtains the parent element, if any. `null` is returned if the element does not have a parent. | | `abstract getParentElement(element: unknown): unknown` Parameters | | | | | --- | --- | --- | | `element` | `unknown` | | Returns `unknown` | | query() | | --- | | `abstract query(element: any, selector: string, multi: boolean): any[]` Parameters | | | | | --- | --- | --- | | `element` | `any` | | | `selector` | `string` | | | `multi` | `boolean` | | Returns `any[]` | | computeStyle() | | --- | | `abstract computeStyle(element: any, prop: string, defaultValue?: string): string` Parameters | | | | | --- | --- | --- | | `element` | `any` | | | `prop` | `string` | | | `defaultValue` | `string` | Optional. Default is `undefined`. | Returns `string` | | animate() | | --- | | `abstract animate(element: any, keyframes: Map<string, string | number>[], duration: number, delay: number, easing?: string, previousPlayers?: any[], scrubberAccessRequested?: boolean): any` Parameters | | | | | --- | --- | --- | | `element` | `any` | | | `[keyframes](../keyframes)` | `Map<string, string | number>[]` | | | `duration` | `number` | | | `delay` | `number` | | | `easing` | `string` | Optional. Default is `undefined`. | | `previousPlayers` | `any[]` | Optional. Default is `undefined`. | | `scrubberAccessRequested` | `boolean` | Optional. Default is `undefined`. | Returns `any` | angular @angular/animations/browser/testing @angular/animations/browser/testing =================================== `entry-point` Provides infrastructure for testing of the Animations browser subsystem. Entry point exports ------------------- ### Classes | | | | --- | --- | | `[MockAnimationDriver](testing/mockanimationdriver)` | | | `[MockAnimationPlayer](testing/mockanimationplayer)` | | angular MockAnimationDriver MockAnimationDriver =================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` ``` class MockAnimationDriver implements AnimationDriver { static log: AnimationPlayer[] validateStyleProperty(prop: string): boolean validateAnimatableStyleProperty(prop: string): boolean matchesElement(_element: any, _selector: string): boolean containsElement(elm1: any, elm2: any): boolean getParentElement(element: unknown): unknown query(element: any, selector: string, multi: boolean): any[] computeStyle(element: any, prop: string, defaultValue?: string): string animate(element: any, keyframes: ɵStyleDataMap[], duration: number, delay: number, easing: string, previousPlayers: any[] = []): MockAnimationPlayer } ``` Static properties ----------------- | Property | Description | | --- | --- | | `[static](../../../upgrade/static) log: [AnimationPlayer](../../animationplayer)[]` | | Methods ------- | validateStyleProperty() | | --- | | `validateStyleProperty(prop: string): boolean` Parameters | | | | | --- | --- | --- | | `prop` | `string` | | Returns `boolean` | | validateAnimatableStyleProperty() | | --- | | `validateAnimatableStyleProperty(prop: string): boolean` Parameters | | | | | --- | --- | --- | | `prop` | `string` | | Returns `boolean` | | matchesElement() | | --- | | `matchesElement(_element: any, _selector: string): boolean` Parameters | | | | | --- | --- | --- | | `_element` | `any` | | | `_selector` | `string` | | Returns `boolean` | | containsElement() | | --- | | `containsElement(elm1: any, elm2: any): boolean` Parameters | | | | | --- | --- | --- | | `elm1` | `any` | | | `elm2` | `any` | | Returns `boolean` | | getParentElement() | | --- | | `getParentElement(element: unknown): unknown` Parameters | | | | | --- | --- | --- | | `element` | `unknown` | | Returns `unknown` | | query() | | --- | | `query(element: any, selector: string, multi: boolean): any[]` Parameters | | | | | --- | --- | --- | | `element` | `any` | | | `selector` | `string` | | | `multi` | `boolean` | | Returns `any[]` | | computeStyle() | | --- | | `computeStyle(element: any, prop: string, defaultValue?: string): string` Parameters | | | | | --- | --- | --- | | `element` | `any` | | | `prop` | `string` | | | `defaultValue` | `string` | Optional. Default is `undefined`. | Returns `string` | | animate() | | --- | | `animate(element: any, keyframes: ɵStyleDataMap[], duration: number, delay: number, easing: string, previousPlayers: any[] = []): MockAnimationPlayer` Parameters | | | | | --- | --- | --- | | `element` | `any` | | | `[keyframes](../../keyframes)` | `ɵStyleDataMap[]` | | | `duration` | `number` | | | `delay` | `number` | | | `easing` | `string` | | | `previousPlayers` | `any[]` | Optional. Default is `[]`. | Returns `[MockAnimationPlayer](mockanimationplayer)` |
programming_docs
angular MockAnimationPlayer MockAnimationPlayer =================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` ``` class MockAnimationPlayer extends NoopAnimationPlayer { constructor(element: any, keyframes: ɵStyleDataMap[], duration: number, delay: number, easing: string, previousPlayers: any[]) previousStyles: ɵStyleDataMap currentSnapshot: ɵStyleDataMap element: any keyframes: Array<ɵStyleDataMap> duration: number delay: number easing: string previousPlayers: any[] onInit(fn: () => any) init() reset() finish(): void destroy(): void triggerMicrotask() play(): void hasStarted() beforeDestroy() // inherited from animations/NoopAnimationPlayer constructor(duration: number = 0, delay: number = 0) parentPlayer: AnimationPlayer | null totalTime: number onStart(fn: () => void): void onDone(fn: () => void): void onDestroy(fn: () => void): void hasStarted(): boolean init(): void play(): void pause(): void restart(): void finish(): void destroy(): void reset(): void setPosition(position: number): void getPosition(): number } ``` Constructor ----------- | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `constructor(element: any, keyframes: ɵStyleDataMap[], duration: number, delay: number, easing: string, previousPlayers: any[])` Parameters | | | | | --- | --- | --- | | `element` | `any` | | | `[keyframes](../../keyframes)` | `ɵStyleDataMap[]` | | | `duration` | `number` | | | `delay` | `number` | | | `easing` | `string` | | | `previousPlayers` | `any[]` | | | Properties ---------- | Property | Description | | --- | --- | | `previousStyles: ɵStyleDataMap` | | | `currentSnapshot: ɵStyleDataMap` | | | `element: any` | Declared in Constructor | | `[keyframes](../../keyframes): Array<ɵStyleDataMap>` | Declared in Constructor | | `duration: number` | Declared in Constructor | | `delay: number` | Declared in Constructor | | `easing: string` | Declared in Constructor | | `previousPlayers: any[]` | Declared in Constructor | Methods ------- | onInit() | | --- | | `onInit(fn: () => any)` Parameters | | | | | --- | --- | --- | | `fn` | `() => any` | | | | init() | | --- | | `init()` Parameters There are no parameters. | | reset() | | --- | | `reset()` Parameters There are no parameters. | | finish() | | --- | | `finish(): void` Parameters There are no parameters. Returns `void` | | destroy() | | --- | | `destroy(): void` Parameters There are no parameters. Returns `void` | | triggerMicrotask() | | --- | | `triggerMicrotask()` Parameters There are no parameters. | | play() | | --- | | `play(): void` Parameters There are no parameters. Returns `void` | | hasStarted() | | --- | | `hasStarted()` Parameters There are no parameters. | | beforeDestroy() | | --- | | `beforeDestroy()` Parameters There are no parameters. | angular UnrecoverableStateEvent UnrecoverableStateEvent ======================= `interface` An event emitted when the version of the app used by the service worker to serve this client is in a broken state that cannot be recovered from and a full page reload is required. [See more...](unrecoverablestateevent#description) ``` interface UnrecoverableStateEvent { type: 'UNRECOVERABLE_STATE' reason: string } ``` See also -------- * [Service worker communication guide](../../guide/service-worker-communications) Description ----------- For example, the service worker may not be able to retrieve a required resource, neither from the cache nor from the server. This could happen if a new version is deployed to the server and the service worker cache has been partially cleaned by the browser, removing some files of a previous app version but not all. Properties ---------- | Property | Description | | --- | --- | | `type: 'UNRECOVERABLE_STATE'` | | | `reason: string` | | angular SwPush SwPush ====== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Subscribe and listen to [Web Push Notifications](https://developer.mozilla.org/en-US/docs/Web/API/Push_API/Best_Practices) through Angular Service Worker. ``` class SwPush { messages: Observable<object> notificationClicks: Observable<{...} subscription: Observable<PushSubscription | null> isEnabled: boolean requestSubscription(options: { serverPublicKey: string; }): Promise<PushSubscription> unsubscribe(): Promise<void> } ``` See also -------- * [Push Notifications](https://developers.google.com/web/fundamentals/codelabs/push-notifications/) * [Angular Push Notifications](https://blog.angular-university.io/angular-push-notifications/) * [MDN: Push API](https://developer.mozilla.org/en-US/docs/Web/API/Push_API) * [MDN: Notifications API](https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API) * [MDN: Web Push API Notifications best practices](https://developer.mozilla.org/en-US/docs/Web/API/Push_API/Best_Practices) Provided in ----------- * [``` ServiceWorkerModule ```](serviceworkermodule) Properties ---------- | Property | Description | | --- | --- | | `messages: Observable<object>` | Read-Only Emits the payloads of the received push notification messages. | | `notificationClicks: Observable<{ action: string; notification: NotificationOptions & { title: string; }; }>` | Read-Only Emits the payloads of the received push notification messages as well as the action the user interacted with. If no action was used the `action` property contains an empty string `''`. Note that the `notification` property does **not** contain a [Notification](https://developer.mozilla.org/en-US/docs/Web/API/Notification) object but rather a [NotificationOptions](https://notifications.spec.whatwg.org/#dictdef-notificationoptions) object that also includes the `title` of the [Notification](https://developer.mozilla.org/en-US/docs/Web/API/Notification) object. | | `subscription: Observable<PushSubscription | null>` | Read-Only Emits the currently active [PushSubscription](https://developer.mozilla.org/en-US/docs/Web/API/PushSubscription) associated to the Service Worker registration or `null` if there is no subscription. | | `isEnabled: boolean` | Read-Only True if the Service Worker is enabled (supported by the browser and enabled via `[ServiceWorkerModule](serviceworkermodule)`). | Methods ------- | requestSubscription() | | --- | | Subscribes to Web Push Notifications, after requesting and receiving user permission. | | `requestSubscription(options: { serverPublicKey: string; }): Promise<PushSubscription>` Parameters | | | | | --- | --- | --- | | `options` | `object` | An object containing the `serverPublicKey` string. | Returns `Promise<PushSubscription>`: A Promise that resolves to the new subscription object. | | unsubscribe() | | --- | | Unsubscribes from Service Worker push notifications. | | `unsubscribe(): Promise<void>` Parameters There are no parameters. Returns `Promise<void>`: A Promise that is resolved when the operation succeeds, or is rejected if there is no active subscription or the unsubscribe operation fails. | Usage notes ----------- You can inject a `[SwPush](swpush)` instance into any component or service as a dependency. ``` import {SwPush} from '@angular/service-worker'; /* . . . */ export class AppComponent { constructor(readonly swPush: SwPush) {} /* . . . */ } ``` To subscribe, call `[SwPush.requestSubscription()](swpush#requestSubscription)`, which asks the user for permission. The call returns a `Promise` with a new [`PushSubscription`](https://developer.mozilla.org/en-US/docs/Web/API/PushSubscription) instance. ``` private async subscribeToPush() { try { const sub = await this.swPush.requestSubscription({ serverPublicKey: PUBLIC_VAPID_KEY_OF_SERVER, }); // TODO: Send to server. } catch (err) { console.error('Could not subscribe due to:', err); } } ``` A request is rejected if the user denies permission, or if the browser blocks or does not support the Push API or ServiceWorkers. Check `[SwPush.isEnabled](swpush#isEnabled)` to confirm status. Invoke Push Notifications by pushing a message with the following payload. ``` { "notification": { "actions": NotificationAction[], "badge": USVString, "body": DOMString, "data": any, "dir": "auto"|"ltr"|"rtl", "icon": USVString, "image": USVString, "lang": DOMString, "renotify": boolean, "requireInteraction": boolean, "silent": boolean, "tag": DOMString, "timestamp": DOMTimeStamp, "title": DOMString, "vibrate": number[] } } ``` Only `title` is required. See `Notification` [instance properties](https://developer.mozilla.org/en-US/docs/Web/API/Notification#Instance_properties). While the subscription is active, Service Worker listens for [PushEvent](https://developer.mozilla.org/en-US/docs/Web/API/PushEvent) occurrences and creates [Notification](https://developer.mozilla.org/en-US/docs/Web/API/Notification) instances in response. Unsubscribe using `[SwPush.unsubscribe()](swpush#unsubscribe)`. An application can subscribe to `[SwPush.notificationClicks](swpush#notificationClicks)` observable to be notified when a user clicks on a notification. For example: ``` this.swPush.notificationClicks.subscribe( ({action, notification}) => { // TODO: Do something in response to notification click. }); ``` You can read more on handling notification clicks in the [Service worker notifications guide](../../guide/service-worker-notifications). angular VersionDetectedEvent VersionDetectedEvent ==================== `interface` An event emitted when the service worker has detected a new version of the app on the server and is about to start downloading it. ``` interface VersionDetectedEvent { type: 'VERSION_DETECTED' version: {...} } ``` See also -------- * [Service worker communication guide](../../guide/service-worker-communications) Properties ---------- | Property | Description | | --- | --- | | `type: 'VERSION_DETECTED'` | | | `version: { hash: string; appData?: object; }` | | angular VersionInstallationFailedEvent VersionInstallationFailedEvent ============================== `interface` An event emitted when the installation of a new version failed. It may be used for logging/monitoring purposes. ``` interface VersionInstallationFailedEvent { type: 'VERSION_INSTALLATION_FAILED' version: {...} error: string } ``` See also -------- * [Service worker communication guide](../../guide/service-worker-communications) Properties ---------- | Property | Description | | --- | --- | | `type: 'VERSION_INSTALLATION_FAILED'` | | | `version: { hash: string; appData?: object; }` | | | `error: string` | | angular SwRegistrationOptions SwRegistrationOptions ===================== `class` Token that can be used to provide options for `[ServiceWorkerModule](serviceworkermodule)` outside of `[ServiceWorkerModule.register()](serviceworkermodule#register)`. [See more...](swregistrationoptions#description) ``` abstract class SwRegistrationOptions { enabled?: boolean scope?: string registrationStrategy?: string | (() => Observable<unknown>) } ``` Description ----------- You can use this token to define a provider that generates the registration options at runtime, for example via a function call: ``` import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {ServiceWorkerModule, SwRegistrationOptions} from '@angular/service-worker'; /* . . . */ @NgModule({ /* . . . */ imports: [ BrowserModule, ServiceWorkerModule.register('ngsw-worker.js'), ], providers: [ { provide: SwRegistrationOptions, useFactory: () => ({enabled: location.search.includes('sw=true')}), }, ], }) export class AppModule { } ``` Properties ---------- | Property | Description | | --- | --- | | `enabled?: boolean` | Whether the ServiceWorker will be registered and the related services (such as `[SwPush](swpush)` and `[SwUpdate](swupdate)`) will attempt to communicate and interact with it. Default: true | | `scope?: string` | A URL that defines the ServiceWorker's registration scope; that is, what range of URLs it can control. It will be used when calling [ServiceWorkerContainer#register()](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register). | | `registrationStrategy?: string | (() => Observable<unknown>)` | Defines the ServiceWorker registration strategy, which determines when it will be registered with the browser. The default behavior of registering once the application stabilizes (i.e. as soon as there are no pending micro- and macro-tasks) is designed to register the ServiceWorker as soon as possible but without affecting the application's first time load. Still, there might be cases where you want more control over when the ServiceWorker is registered (for example, there might be a long-running timeout or polling interval, preventing the app from stabilizing). The available option are:* `registerWhenStable:<timeout>`: Register as soon as the application stabilizes (no pending micro-/macro-tasks) but no later than `<timeout>` milliseconds. If the app hasn't stabilized after `<timeout>` milliseconds (for example, due to a recurrent asynchronous task), the ServiceWorker will be registered anyway. If `<timeout>` is omitted, the ServiceWorker will only be registered once the app stabilizes. * `registerImmediately`: Register immediately. * `registerWithDelay:<timeout>`: Register with a delay of `<timeout>` milliseconds. For example, use `registerWithDelay:5000` to register the ServiceWorker after 5 seconds. If `<timeout>` is omitted, is defaults to `0`, which will register the ServiceWorker as soon as possible but still asynchronously, once all pending micro-tasks are completed. * An [Observable](../../guide/observables) factory function: A function that returns an `Observable`. The function will be used at runtime to obtain and subscribe to the `Observable` and the ServiceWorker will be registered as soon as the first value is emitted. Default: 'registerWhenStable:30000' | angular VersionEvent VersionEvent ============ `type-alias` A union of all event types that can be emitted by [SwUpdate#versionUpdates](swupdate#versionUpdates). ``` type VersionEvent = VersionDetectedEvent | VersionInstallationFailedEvent | VersionReadyEvent | NoNewVersionDetectedEvent; ``` angular UpdateActivatedEvent UpdateActivatedEvent ==================== `interface` `deprecated` An event emitted when a new version of the app has been downloaded and activated. **Deprecated:** This event is only emitted by the deprecated [`SwUpdate`](swupdate#activated). Use the return value of [`SwUpdate`](swupdate#activateUpdate) instead. ``` interface UpdateActivatedEvent { type: 'UPDATE_ACTIVATED' previous?: {...} current: {...} } ``` See also -------- * [Service worker communication guide](../../guide/service-worker-communications) Properties ---------- | Property | Description | | --- | --- | | `type: 'UPDATE_ACTIVATED'` | | | `previous?: { hash: string; appData?: Object; }` | | | `current: { hash: string; appData?: Object; }` | | angular UpdateAvailableEvent UpdateAvailableEvent ==================== `interface` `deprecated` An event emitted when a new version of the app is available. **Deprecated:** This event is only emitted by the deprecated [`SwUpdate`](swupdate#available). Use the [`VersionReadyEvent`](versionreadyevent) instead, which is emitted by [`SwUpdate`](swupdate#versionUpdates). See [`SwUpdate`](swupdate#available) docs for an example. ``` interface UpdateAvailableEvent { type: 'UPDATE_AVAILABLE' current: {...} available: {...} } ``` See also -------- * [Service worker communication guide](../../guide/service-worker-communications) Properties ---------- | Property | Description | | --- | --- | | `type: 'UPDATE_AVAILABLE'` | | | `current: { hash: string; appData?: Object; }` | | | `available: { hash: string; appData?: Object; }` | | angular VersionReadyEvent VersionReadyEvent ================= `interface` An event emitted when a new version of the app is available. ``` interface VersionReadyEvent { type: 'VERSION_READY' currentVersion: {...} latestVersion: {...} } ``` See also -------- * [Service worker communication guide](../../guide/service-worker-communications) Properties ---------- | Property | Description | | --- | --- | | `type: 'VERSION_READY'` | | | `currentVersion: { hash: string; appData?: object; }` | | | `latestVersion: { hash: string; appData?: object; }` | | angular NoNewVersionDetectedEvent NoNewVersionDetectedEvent ========================= `interface` An event emitted when the service worker has checked the version of the app on the server and it didn't find a new version that it doesn't have already downloaded. ``` interface NoNewVersionDetectedEvent { type: 'NO_NEW_VERSION_DETECTED' version: {...} } ``` See also -------- * [Service worker communication guide](../../guide/service-worker-communications) Properties ---------- | Property | Description | | --- | --- | | `type: 'NO_NEW_VERSION_DETECTED'` | | | `version: { hash: string; appData?: Object; }` | | angular SwUpdate SwUpdate ======== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Subscribe to update notifications from the Service Worker, trigger update checks, and forcibly activate updates. ``` class SwUpdate { versionUpdates: Observable<VersionEvent> available: Observable<UpdateAvailableEvent> activated: Observable<UpdateActivatedEvent> unrecoverable: Observable<UnrecoverableStateEvent> isEnabled: boolean checkForUpdate(): Promise<boolean> activateUpdate(): Promise<boolean> } ``` See also -------- * [Service worker communication guide](../../guide/service-worker-communications) Provided in ----------- * [``` ServiceWorkerModule ```](serviceworkermodule) Properties ---------- | Property | Description | | --- | --- | | `versionUpdates: Observable<[VersionEvent](versionevent)>` | Read-Only Emits a `[VersionDetectedEvent](versiondetectedevent)` event whenever a new version is detected on the server. Emits a `[VersionInstallationFailedEvent](versioninstallationfailedevent)` event whenever checking for or downloading a new version fails. Emits a `[VersionReadyEvent](versionreadyevent)` event whenever a new version has been downloaded and is ready for activation. | | `available: Observable<[UpdateAvailableEvent](updateavailableevent)>` | Read-Only Emits an `[UpdateAvailableEvent](updateavailableevent)` event whenever a new app version is available. **Deprecated** Use [`versionUpdates`](swupdate#versionUpdates) instead. The behavior of `available` can be replicated by using `versionUpdates` by filtering for the `[VersionReadyEvent](versionreadyevent)`: ``` import { filter, map } from 'rxjs/operators'; // ... const updatesAvailable = swUpdate.versionUpdates.pipe( filter((evt): evt is VersionReadyEvent => evt.type === 'VERSION_READY'), map(evt => ({ type: 'UPDATE_AVAILABLE', current: evt.currentVersion, available: evt.latestVersion, }))); ``` | | `activated: Observable<[UpdateActivatedEvent](updateactivatedevent)>` | Read-Only Emits an `[UpdateActivatedEvent](updateactivatedevent)` event whenever the app has been updated to a new version. **Deprecated** Use the return value of [`SwUpdate`](swupdate#activateUpdate) instead. | | `unrecoverable: Observable<[UnrecoverableStateEvent](unrecoverablestateevent)>` | Read-Only Emits an `[UnrecoverableStateEvent](unrecoverablestateevent)` event whenever the version of the app used by the service worker to serve this client is in a broken state that cannot be recovered from without a full page reload. | | `isEnabled: boolean` | Read-Only True if the Service Worker is enabled (supported by the browser and enabled via `[ServiceWorkerModule](serviceworkermodule)`). | Methods ------- | checkForUpdate() | | --- | | Checks for an update and waits until the new version is downloaded from the server and ready for activation. | | `checkForUpdate(): Promise<boolean>` Parameters There are no parameters. Returns `Promise<boolean>`: a promise that * resolves to `true` if a new version was found and is ready to be activated. * resolves to `false` if no new version was found * rejects if any error occurs | | activateUpdate() | | --- | | Updates the current client (i.e. browser tab) to the latest version that is ready for activation. | | `activateUpdate(): Promise<boolean>` Parameters There are no parameters. Returns `Promise<boolean>`: a promise that * resolves to `true` if an update was activated successfully * resolves to `false` if no update was available (for example, the client was already on the latest version). * rejects if any error occurs | | In most cases, you should not use this method and instead should update a client by reloading the page. Updating a client without reloading can easily result in a broken application due to a version mismatch between the [application shell](../../guide/glossary#app-shell) and other page resources, such as [lazy-loaded chunks](../../guide/glossary#lazy-loading), whose filenames may change between versions. Only use this method, if you are certain it is safe for your specific use case. |
programming_docs
angular ServiceWorkerModule ServiceWorkerModule =================== `ngmodule` ``` class ServiceWorkerModule { static register(script: string, opts: SwRegistrationOptions = {}): ModuleWithProviders<ServiceWorkerModule> } ``` Static methods -------------- | register() | | --- | | Register the given Angular Service Worker script. | | `static register(script: string, opts: SwRegistrationOptions = {}): ModuleWithProviders<ServiceWorkerModule>` Parameters | | | | | --- | --- | --- | | `script` | `string` | | | `opts` | `[SwRegistrationOptions](swregistrationoptions)` | Optional. Default is `{}`. | Returns `[ModuleWithProviders](../core/modulewithproviders)<[ServiceWorkerModule](serviceworkermodule)>` | | If `enabled` is set to `false` in the given options, the module will behave as if service workers are not supported by the browser, and the service worker will not be registered. | Providers --------- | Provider | | --- | | ``` SwPush ``` | | ``` SwUpdate ``` | angular Meta Meta ==== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A service for managing HTML `<meta>` tags. [See more...](meta#description) ``` class Meta { addTag(tag: MetaDefinition, forceCreation: boolean = false): HTMLMetaElement | null addTags(tags: MetaDefinition[], forceCreation: boolean = false): HTMLMetaElement[] getTag(attrSelector: string): HTMLMetaElement | null getTags(attrSelector: string): HTMLMetaElement[] updateTag(tag: MetaDefinition, selector?: string): HTMLMetaElement | null removeTag(attrSelector: string): void removeTagElement(meta: HTMLMetaElement): void } ``` See also -------- * [HTML meta tag](https://developer.mozilla.org/docs/Web/HTML/Element/meta) * [Document.querySelector()](https://developer.mozilla.org/docs/Web/API/Document/querySelector) Provided in ----------- * ``` 'root' ``` Description ----------- Properties of the `[MetaDefinition](metadefinition)` object match the attributes of the HTML `<meta>` tag. These tags define document metadata that is important for things like configuring a Content Security Policy, defining browser compatibility and security settings, setting HTTP Headers, defining rich content for social sharing, and Search Engine Optimization (SEO). To identify specific `<meta>` tags in a document, use an attribute selection string in the format `"tag_attribute='value string'"`. For example, an `attrSelector` value of `"name='description'"` matches a tag whose `name` attribute has the value `"description"`. Selectors are used with the `querySelector()` Document method, in the format `meta[{attrSelector}]`. Methods ------- | addTag() | | --- | | Retrieves or creates a specific `<meta>` tag element in the current HTML document. In searching for an existing tag, Angular attempts to match the `name` or `property` attribute values in the provided tag definition, and verifies that all other attribute values are equal. If an existing element is found, it is returned and is not modified in any way. | | `addTag(tag: MetaDefinition, forceCreation: boolean = false): HTMLMetaElement | null` Parameters | | | | | --- | --- | --- | | `tag` | `[MetaDefinition](metadefinition)` | The definition of a `<meta>` element to match or create. | | `forceCreation` | `boolean` | True to create a new element without checking whether one already exists. Optional. Default is `false`. | Returns `HTMLMetaElement | null`: The existing element with the same attributes and values if found, the new element if no match is found, or `null` if the tag parameter is not defined. | | addTags() | | --- | | Retrieves or creates a set of `<meta>` tag elements in the current HTML document. In searching for an existing tag, Angular attempts to match the `name` or `property` attribute values in the provided tag definition, and verifies that all other attribute values are equal. | | `addTags(tags: MetaDefinition[], forceCreation: boolean = false): HTMLMetaElement[]` Parameters | | | | | --- | --- | --- | | `tags` | `[MetaDefinition](metadefinition)[]` | An array of tag definitions to match or create. | | `forceCreation` | `boolean` | True to create new elements without checking whether they already exist. Optional. Default is `false`. | Returns `HTMLMetaElement[]`: The matching elements if found, or the new elements. | | getTag() | | --- | | Retrieves a `<meta>` tag element in the current HTML document. | | `getTag(attrSelector: string): HTMLMetaElement | null` Parameters | | | | | --- | --- | --- | | `attrSelector` | `string` | The tag attribute and value to match against, in the format `"tag_attribute='value string'"`. | Returns `HTMLMetaElement | null`: The matching element, if any. | | getTags() | | --- | | Retrieves a set of `<meta>` tag elements in the current HTML document. | | `getTags(attrSelector: string): HTMLMetaElement[]` Parameters | | | | | --- | --- | --- | | `attrSelector` | `string` | The tag attribute and value to match against, in the format `"tag_attribute='value string'"`. | Returns `HTMLMetaElement[]`: The matching elements, if any. | | updateTag() | | --- | | Modifies an existing `<meta>` tag element in the current HTML document. | | `updateTag(tag: MetaDefinition, selector?: string): HTMLMetaElement | null` Parameters | | | | | --- | --- | --- | | `tag` | `[MetaDefinition](metadefinition)` | The tag description with which to replace the existing tag content. | | `selector` | `string` | A tag attribute and value to match against, to identify an existing tag. A string in the format `"tag_attribute=`value string`"`. If not supplied, matches a tag with the same `name` or `property` attribute value as the replacement tag. Optional. Default is `undefined`. | Returns `HTMLMetaElement | null`: The modified element. | | removeTag() | | --- | | Removes an existing `<meta>` tag element from the current HTML document. | | `removeTag(attrSelector: string): void` Parameters | | | | | --- | --- | --- | | `attrSelector` | `string` | A tag attribute and value to match against, to identify an existing tag. A string in the format `"tag_attribute=`value string`"`. | Returns `void` | | removeTagElement() | | --- | | Removes an existing `<meta>` tag element from the current HTML document. | | `removeTagElement(meta: HTMLMetaElement): void` Parameters | | | | | --- | --- | --- | | `meta` | `HTMLMetaElement` | The tag definition to match against to identify an existing tag. | Returns `void` | angular SafeStyle SafeStyle ========= `interface` Marker interface for a value that's safe to use as style (CSS). ``` interface SafeStyle extends SafeValue { // inherited from platform-browser/SafeValue } ``` angular createApplication createApplication ================= `function` Create an instance of an Angular application without bootstrapping any components. This is useful for the situation where one wants to decouple application environment creation (a platform and associated injectors) from rendering components on a screen. Components can be subsequently bootstrapped on the returned `[ApplicationRef](../core/applicationref)`. ### `createApplication(options?: ApplicationConfig)` ###### Parameters | | | | | --- | --- | --- | | `options` | `[ApplicationConfig](applicationconfig)` | Extra configuration for the application environment, see `[ApplicationConfig](applicationconfig)` for additional info. Optional. Default is `undefined`. | angular ApplicationConfig ApplicationConfig ================= `interface` Set of config options available during the application bootstrap operation. ``` interface ApplicationConfig { providers: Array<Provider | EnvironmentProviders> } ``` Properties ---------- | Property | Description | | --- | --- | | `providers: Array<[Provider](../core/provider) | [EnvironmentProviders](../core/environmentproviders)>` | List of providers that should be available to the root component and all its children. | angular By By == `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Predicates for use with [`DebugElement`](../core/debugelement)'s query functions. ``` class By { static all(): Predicate<DebugNode> static css(selector: string): Predicate<DebugElement> static directive(type: Type<any>): Predicate<DebugNode> } ``` Static methods -------------- | all() | | --- | | Match all nodes. | | `static all(): Predicate<DebugNode>` Parameters There are no parameters. Returns `[Predicate](../core/predicate)<[DebugNode](../core/debugnode)>` | | Usage Notes Example ``` debugElement.query(By.all()); ``` | | css() | | --- | | Match elements by the given CSS selector. | | `static css(selector: string): Predicate<DebugElement>` Parameters | | | | | --- | --- | --- | | `selector` | `string` | | Returns `[Predicate](../core/predicate)<[DebugElement](../core/debugelement)>` | | Usage Notes Example ``` debugElement.query(By.css('[attribute]')); ``` | | directive() | | --- | | Match nodes that have the given directive present. | | `static directive(type: Type<any>): Predicate<DebugNode>` Parameters | | | | | --- | --- | --- | | `type` | `[Type](../core/type)<any>` | | Returns `[Predicate](../core/predicate)<[DebugNode](../core/debugnode)>` | | Usage Notes Example ``` debugElement.query(By.directive(MyDirective)); ``` | angular disableDebugTools disableDebugTools ================= `function` Disables Angular tools. ### `disableDebugTools(): void` ###### Parameters There are no parameters. ###### Returns `void` angular SafeScript SafeScript ========== `interface` Marker interface for a value that's safe to use as JavaScript. ``` interface SafeScript extends SafeValue { // inherited from platform-browser/SafeValue } ``` angular makeStateKey makeStateKey ============ `function` Create a `[StateKey](statekey)<T>` that can be used to store value of type T with `[TransferState](transferstate)`. [See more...](makestatekey#description) ### `makeStateKey<T = void>(key: string): StateKey<T>` ###### Parameters | | | | | --- | --- | --- | | `key` | `string` | | ###### Returns `[StateKey](statekey)<T>` Description ----------- Example: ``` const COUNTER_KEY = makeStateKey<number>('counter'); let value = 10; transferState.set(COUNTER_KEY, value); ``` angular platformBrowser platformBrowser =============== `const` A factory function that returns a `[PlatformRef](../core/platformref)` instance associated with browser service providers. ### `const platformBrowser: (extraProviders?: StaticProvider[]) => PlatformRef;` angular BrowserTransferStateModule BrowserTransferStateModule ========================== `ngmodule` `deprecated` NgModule to install on the client side while using the `[TransferState](transferstate)` to transfer state from server to client. **Deprecated:** no longer needed, you can inject the `[TransferState](transferstate)` in an app without providing this module. ``` class BrowserTransferStateModule { } ``` angular SafeHtml SafeHtml ======== `interface` Marker interface for a value that's safe to use as HTML. ``` interface SafeHtml extends SafeValue { // inherited from platform-browser/SafeValue } ``` angular BrowserModule BrowserModule ============= `ngmodule` Exports required infrastructure for all Angular apps. Included by default in all Angular apps created with the CLI `new` command. Re-exports `[CommonModule](../common/commonmodule)` and `[ApplicationModule](../core/applicationmodule)`, making their exports and providers available to all apps. ``` class BrowserModule { static withServerTransition(params: { appId: string; }): ModuleWithProviders<BrowserModule> } ``` Static methods -------------- | withServerTransition() | | --- | | Configures a browser-based app to transition from a server-rendered app, if one is present on the page. | | `static withServerTransition(params: { appId: string; }): ModuleWithProviders<BrowserModule>` Parameters | | | | | --- | --- | --- | | `params` | `{ appId: string; }` | An object containing an identifier for the app to transition. The ID must match between the client and server versions of the app. | Returns `[ModuleWithProviders](../core/modulewithproviders)<[BrowserModule](browsermodule)>`: The reconfigured `[BrowserModule](browsermodule)` to import into the app's root `AppModule`. | Providers --------- | Provider | | --- | | ``` ...BROWSER_MODULE_PROVIDERS ``` | | ``` ...TESTABILITY_PROVIDERS ``` | angular Title Title ===== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A service that can be used to get and set the title of a current HTML document. [See more...](title#description) ``` class Title { getTitle(): string setTitle(newTitle: string) } ``` Provided in ----------- * ``` 'root' ``` Description ----------- Since an Angular application can't be bootstrapped on the entire HTML document (`<html>` tag) it is not possible to bind to the `text` property of the `HTMLTitleElement` elements (representing the `<title>` tag). Instead, this service can be used to set and get the current title value. Methods ------- | getTitle() | | --- | | Get the title of the current HTML document. | | `getTitle(): string` Parameters There are no parameters. Returns `string` | | setTitle() | | --- | | Set the title of the current HTML document. | | `setTitle(newTitle: string)` Parameters | | | | | --- | --- | --- | | `newTitle` | `string` | | | angular EventManager EventManager ============ `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An injectable service that provides event management for Angular through a browser plug-in. ``` class EventManager { constructor(plugins: EventManagerPlugin[], _zone: NgZone) addEventListener(element: HTMLElement, eventName: string, handler: Function): Function addGlobalEventListener(target: string, eventName: string, handler: Function): Function getZone(): NgZone } ``` Constructor ----------- | | | --- | | Initializes an instance of the event-manager service. This class is "final" and should not be extended. See the [public API notes](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes). | | `constructor(plugins: EventManagerPlugin[], _zone: NgZone)` Parameters | | | | | --- | --- | --- | | `plugins` | `EventManagerPlugin[]` | | | `_zone` | `[NgZone](../core/ngzone)` | | | Methods ------- | addEventListener() | | --- | | Registers a handler for a specific element and event. | | `addEventListener(element: HTMLElement, eventName: string, handler: Function): Function` Parameters | | | | | --- | --- | --- | | `element` | `HTMLElement` | The HTML element to receive event notifications. | | `eventName` | `string` | The name of the event to listen for. | | `handler` | `Function` | A function to call when the notification occurs. Receives the event object as an argument. | Returns `Function`: A callback function that can be used to remove the handler. | | addGlobalEventListener() | | --- | | Registers a global handler for an event in a target view. | | `addGlobalEventListener(target: string, eventName: string, handler: Function): Function` **Deprecated** No longer being used in Ivy code. To be removed in version 14. Parameters | | | | | --- | --- | --- | | `target` | `string` | A target for global event notifications. One of "window", "document", or "body". | | `eventName` | `string` | The name of the event to listen for. | | `handler` | `Function` | A function to call when the notification occurs. Receives the event object as an argument. | Returns `Function`: A callback function that can be used to remove the handler. | | getZone() | | --- | | Retrieves the compilation zone in which event listeners are registered. | | `getZone(): NgZone` Parameters There are no parameters. Returns `[NgZone](../core/ngzone)` | angular SafeValue SafeValue ========= `interface` Marker interface for a value that's safe to use in a particular context. ``` interface SafeValue { } ``` Child interfaces ---------------- * `[SafeHtml](safehtml)` * `[SafeResourceUrl](saferesourceurl)` * `[SafeScript](safescript)` * `[SafeStyle](safestyle)` * `[SafeUrl](safeurl)` angular bootstrapApplication bootstrapApplication ==================== `function` Bootstraps an instance of an Angular application and renders a standalone component as the application's root component. More information about standalone components can be found in [this guide](../../guide/standalone-components). ### `bootstrapApplication(rootComponent: Type<unknown>, options?: ApplicationConfig): Promise<ApplicationRef>` ###### Parameters | | | | | --- | --- | --- | | `rootComponent` | `[Type](../core/type)<unknown>` | A reference to a standalone component that should be rendered. | | `options` | `[ApplicationConfig](applicationconfig)` | Extra configuration for the bootstrap operation, see `[ApplicationConfig](applicationconfig)` for additional info. Optional. Default is `undefined`. | ###### Returns `Promise<[ApplicationRef](../core/applicationref)>`: A promise that returns an `[ApplicationRef](../core/applicationref)` instance once resolved. Usage notes ----------- The root component passed into this function *must* be a standalone one (should have the `standalone: true` flag in the `@[Component](../core/component)` decorator config). ``` @Component({ standalone: true, template: 'Hello world!' }) class RootComponent {} const appRef: ApplicationRef = await bootstrapApplication(RootComponent); ``` You can add the list of providers that should be available in the application injector by specifying the `providers` field in an object passed as the second argument: ``` await bootstrapApplication(RootComponent, { providers: [ {provide: BACKEND_URL, useValue: 'https://yourdomain.com/api'} ] }); ``` The `[importProvidersFrom](../core/importprovidersfrom)` helper method can be used to collect all providers from any existing NgModule (and transitively from all NgModules that it imports): ``` await bootstrapApplication(RootComponent, { providers: [ importProvidersFrom(SomeNgModule) ] }); ``` Note: the `[bootstrapApplication](bootstrapapplication)` method doesn't include [Testability](../core/testability) by default. You can add [Testability](../core/testability) by getting the list of necessary providers using `[provideProtractorTestingSupport](provideprotractortestingsupport)()` function and adding them into the `providers` array, for example: ``` import {provideProtractorTestingSupport} from '@angular/platform-browser'; await bootstrapApplication(RootComponent, {providers: [provideProtractorTestingSupport()]}); ``` angular HammerGestureConfig HammerGestureConfig =================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An injectable [HammerJS Manager](https://hammerjs.github.io/api/#hammermanager) for gesture recognition. Configures specific event recognition. ``` class HammerGestureConfig { events: string[] overrides: {...} options?: {...} buildHammer(element: HTMLElement): HammerInstance } ``` Properties ---------- | Property | Description | | --- | --- | | `events: string[]` | A set of supported event names for gestures to be used in Angular. Angular supports all built-in recognizers, as listed in [HammerJS documentation](https://hammerjs.github.io/). | | `overrides: { [key: string]: Object; }` | Maps gesture event names to a set of configuration options that specify overrides to the default values for specific properties. The key is a supported event name to be configured, and the options object contains a set of properties, with override values to be applied to the named recognizer event. For example, to disable recognition of the rotate event, specify `{"rotate": {"enable": false}}`. Properties that are not present take the HammerJS default values. For information about which properties are supported for which events, and their allowed and default values, see [HammerJS documentation](https://hammerjs.github.io/). | | `options?: { cssProps?: any; domEvents?: boolean; enable?: boolean | ((manager: any) => boolean); preset?: any[]; touchAction?: string; recognizers?: any[]; inputClass?: any; inputTarget?: EventTarget; }` | Properties whose default values can be overridden for a given event. Different sets of properties apply to different events. For information about which properties are supported for which events, and their allowed and default values, see [HammerJS documentation](https://hammerjs.github.io/). | Methods ------- | buildHammer() | | --- | | Creates a [HammerJS Manager](https://hammerjs.github.io/api/#hammermanager) and attaches it to a given HTML element. | | `buildHammer(element: HTMLElement): HammerInstance` Parameters | | | | | --- | --- | --- | | `element` | `HTMLElement` | The element that will recognize gestures. | Returns `HammerInstance`: A HammerJS event-manager object. |
programming_docs
angular SafeResourceUrl SafeResourceUrl =============== `interface` Marker interface for a value that's safe to use as a URL to load executable code from. ``` interface SafeResourceUrl extends SafeValue { // inherited from platform-browser/SafeValue } ``` angular SafeUrl SafeUrl ======= `interface` Marker interface for a value that's safe to use as a URL linking to a document. ``` interface SafeUrl extends SafeValue { // inherited from platform-browser/SafeValue } ``` angular provideProtractorTestingSupport provideProtractorTestingSupport =============================== `function` Returns a set of providers required to setup [Testability](../core/testability) for an application bootstrapped using the `[bootstrapApplication](bootstrapapplication)` function. The set of providers is needed to support testing an application with Protractor (which relies on the Testability APIs to be present). ### `provideProtractorTestingSupport(): Provider[]` ###### Parameters There are no parameters. ###### Returns `[Provider](../core/provider)[]`: An array of providers required to setup Testability for an application and make it available for testing using Protractor. angular HammerLoader HammerLoader ============ `type-alias` Function that loads HammerJS, returning a promise that is resolved once HammerJs is loaded. ``` type HammerLoader = () => Promise<void>; ``` angular DomSanitizer DomSanitizer ============ `class` `security` DomSanitizer helps preventing Cross Site Scripting Security bugs (XSS) by sanitizing values to be safe to use in the different DOM contexts. [See more...](domsanitizer#description) Security risk ------------- Calling any of the `bypassSecurityTrust...` APIs disables Angular's built-in sanitization for the value passed in. Carefully check and audit all values and code paths going into this call. Make sure any user data is appropriately escaped for this security context. For more detail, see the [Security Guide](https://g.co/ng/security). ``` abstract class DomSanitizer implements Sanitizer { abstract sanitize(context: SecurityContext, value: string | SafeValue): string | null abstract bypassSecurityTrustHtml(value: string): SafeHtml abstract bypassSecurityTrustStyle(value: string): SafeStyle abstract bypassSecurityTrustScript(value: string): SafeScript abstract bypassSecurityTrustUrl(value: string): SafeUrl abstract bypassSecurityTrustResourceUrl(value: string): SafeResourceUrl } ``` Provided in ----------- * ``` 'root' ``` Description ----------- For example, when binding a URL in an `<a [href]="someValue">` hyperlink, `someValue` will be sanitized so that an attacker cannot inject e.g. a `javascript:` URL that would execute code on the website. In specific situations, it might be necessary to disable sanitization, for example if the application genuinely needs to produce a `javascript:` style link with a dynamic value in it. Users can bypass security by constructing a value with one of the `bypassSecurityTrust...` methods, and then binding to that value from the template. These situations should be very rare, and extraordinary care must be taken to avoid creating a Cross Site Scripting (XSS) security bug! When using `bypassSecurityTrust...`, make sure to call the method as early as possible and as close as possible to the source of the value, to make it easy to verify no security bug is created by its use. It is not required (and not recommended) to bypass security if the value is safe, e.g. a URL that does not start with a suspicious protocol, or an HTML snippet that does not contain dangerous code. The sanitizer leaves safe values intact. Methods ------- | sanitize() | | --- | | Gets a safe value from either a known safe value or a value with unknown safety. | | `abstract sanitize(context: SecurityContext, value: string | SafeValue): string | null` Parameters | | | | | --- | --- | --- | | `context` | `[SecurityContext](../core/securitycontext)` | | | `value` | `string | [SafeValue](safevalue)` | | Returns `string | null` | | If the given value is already a `[SafeValue](safevalue)`, this method returns the unwrapped value. If the security context is HTML and the given value is a plain string, this method sanitizes the string, removing any potentially unsafe content. For any other security context, this method throws an error if provided with a plain string. | | bypassSecurityTrustHtml() | | --- | | Bypass security and trust the given value to be safe HTML. Only use this when the bound HTML is unsafe (e.g. contains `<script>` tags) and the code should be executed. The sanitizer will leave safe HTML intact, so in most situations this method should not be used. | | `abstract bypassSecurityTrustHtml(value: string): SafeHtml` Parameters | | | | | --- | --- | --- | | `value` | `string` | | Returns `[SafeHtml](safehtml)` | | **WARNING:** calling this method with untrusted user data exposes your application to XSS security risks! | | bypassSecurityTrustStyle() | | --- | | Bypass security and trust the given value to be safe style value (CSS). | | `abstract bypassSecurityTrustStyle(value: string): SafeStyle` Parameters | | | | | --- | --- | --- | | `value` | `string` | | Returns `[SafeStyle](safestyle)` | | **WARNING:** calling this method with untrusted user data exposes your application to XSS security risks! | | bypassSecurityTrustScript() | | --- | | Bypass security and trust the given value to be safe JavaScript. | | `abstract bypassSecurityTrustScript(value: string): SafeScript` Parameters | | | | | --- | --- | --- | | `value` | `string` | | Returns `[SafeScript](safescript)` | | **WARNING:** calling this method with untrusted user data exposes your application to XSS security risks! | | bypassSecurityTrustUrl() | | --- | | Bypass security and trust the given value to be a safe style URL, i.e. a value that can be used in hyperlinks or `<[img](../common/ngoptimizedimage) src>`. | | `abstract bypassSecurityTrustUrl(value: string): SafeUrl` Parameters | | | | | --- | --- | --- | | `value` | `string` | | Returns `[SafeUrl](safeurl)` | | **WARNING:** calling this method with untrusted user data exposes your application to XSS security risks! | | bypassSecurityTrustResourceUrl() | | --- | | Bypass security and trust the given value to be a safe resource URL, i.e. a location that may be used to load executable code from, like `<script src>`, or `<iframe src>`. | | `abstract bypassSecurityTrustResourceUrl(value: string): SafeResourceUrl` Parameters | | | | | --- | --- | --- | | `value` | `string` | | Returns `[SafeResourceUrl](saferesourceurl)` | | **WARNING:** calling this method with untrusted user data exposes your application to XSS security risks! | angular HammerModule HammerModule ============ `ngmodule` Adds support for HammerJS. [See more...](hammermodule#description) ``` class HammerModule { } ``` Description ----------- Import this module at the root of your application so that Angular can work with HammerJS to detect gesture events. Note that applications still need to include the HammerJS script itself. This module simply sets up the coordination layer between HammerJS and Angular's EventManager. Providers --------- | Provider | | --- | | ``` { provide: EVENT_MANAGER_PLUGINS, useClass: HammerGesturesPlugin, multi: true, deps: [DOCUMENT, HAMMER_GESTURE_CONFIG, Console, [new Optional(), HAMMER_LOADER]] } ``` | | ``` { provide: HAMMER_GESTURE_CONFIG, useClass: HammerGestureConfig, deps: [] } ``` | angular HAMMER_GESTURE_CONFIG HAMMER\_GESTURE\_CONFIG ======================= `const` DI token for providing [HammerJS](https://hammerjs.github.io/) support to Angular. ### `const HAMMER_GESTURE_CONFIG: InjectionToken<HammerGestureConfig>;` #### See also * `[HammerGestureConfig](hammergestureconfig)` angular EVENT_MANAGER_PLUGINS EVENT\_MANAGER\_PLUGINS ======================= `const` The injection token for the event-manager plug-in service. ### `const EVENT_MANAGER_PLUGINS: InjectionToken<EventManagerPlugin[]>;` angular StateKey StateKey ======== `type-alias` A type-safe key to use with `[TransferState](transferstate)`. [See more...](statekey#description) ``` type StateKey<T> = string & { __not_a_string: never; __value_type?: T; }; ``` Description ----------- Example: ``` const COUNTER_KEY = makeStateKey<number>('counter'); let value = 10; transferState.set(COUNTER_KEY, value); ``` angular @angular/platform-browser/animations @angular/platform-browser/animations ==================================== `entry-point` Provides infrastructure for the rendering of animations in supported browsers. Entry point exports ------------------- ### NgModules | | | | --- | --- | | `[BrowserAnimationsModule](animations/browseranimationsmodule)` | Exports `[BrowserModule](browsermodule)` with additional [dependency-injection providers](../../guide/glossary#provider) for use with animations. See [Animations](../../guide/animations). | | `[NoopAnimationsModule](animations/noopanimationsmodule)` | A null player that must be imported to allow disabling of animations. | ### Functions | | | | --- | --- | | `[provideAnimations](animations/provideanimations)` | Returns the set of [dependency-injection providers](../../guide/glossary#provider) to enable animations in an application. See [animations guide](../../guide/animations) to learn more about animations in Angular. | | `[provideNoopAnimations](animations/providenoopanimations)` | Returns the set of [dependency-injection providers](../../guide/glossary#provider) to disable animations in an application. See [animations guide](../../guide/animations) to learn more about animations in Angular. | ### Structures | | | | --- | --- | | `[BrowserAnimationsModuleConfig](animations/browseranimationsmoduleconfig)` | Object used to configure the behavior of [`BrowserAnimationsModule`](animations/browseranimationsmodule) | ### Types | | | | --- | --- | | `[ANIMATION\_MODULE\_TYPE](animations/animation_module_type)` | A [DI token](../../guide/glossary#di-token "DI token definition") that indicates which animations module has been loaded. | angular @angular/platform-browser/testing @angular/platform-browser/testing ================================= `entry-point` Supplies a testing module for the Angular platform-browser subsystem. Entry point exports ------------------- ### NgModules | | | | --- | --- | | `[BrowserTestingModule](testing/browsertestingmodule)` | NgModule for testing. | ### Types | | | | --- | --- | | `[platformBrowserTesting](testing/platformbrowsertesting)` | Platform for testing | angular HAMMER_LOADER HAMMER\_LOADER ============== `const` Injection token used to provide a [`HammerLoader`](hammerloader) to Angular. ### `const HAMMER_LOADER: InjectionToken<HammerLoader>;` angular MetaDefinition MetaDefinition ============== `type-alias` Represents the attributes of an HTML `<meta>` element. The element itself is represented by the internal `HTMLMetaElement`. ``` type MetaDefinition = { charset?: string; content?: string; httpEquiv?: string; id?: string; itemprop?: string; name?: string; property?: string; scheme?: string; url?: string; } & { [prop: string]: string; }; ``` See also -------- * [HTML meta tag](https://developer.mozilla.org/docs/Web/HTML/Element/meta) * `[Meta](meta)` angular enableDebugTools enableDebugTools ================ `function` Enabled Angular debug tools that are accessible via your browser's developer console. [See more...](enabledebugtools#description) ### `enableDebugTools<T>(ref: ComponentRef<T>): ComponentRef<T>` ###### Parameters | | | | | --- | --- | --- | | `ref` | `[ComponentRef](../core/componentref)<T>` | | ###### Returns `[ComponentRef](../core/componentref)<T>` Description ----------- Usage: 1. Open developer console (e.g. in Chrome Ctrl + Shift + j) 2. Type `ng.` (usually the console will show auto-complete suggestion) 3. Try the change detection profiler `ng.profiler.timeChangeDetection()` then hit Enter. angular TransferState TransferState ============= `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A key value store that is transferred from the application on the server side to the application on the client side. [See more...](transferstate#description) ``` class TransferState { isEmpty: boolean get<T>(key: StateKey<T>, defaultValue: T): T set<T>(key: StateKey<T>, value: T): void remove<T>(key: StateKey<T>): void hasKey<T>(key: StateKey<T>) onSerialize<T>(key: StateKey<T>, callback: () => T): void toJson(): string } ``` Provided in ----------- * ``` 'root' ``` Description ----------- The `[TransferState](transferstate)` is available as an injectable token. On the client, just inject this token using DI and use it, it will be lazily initialized. On the server it's already included if `[renderApplication](../platform-server/renderapplication)` function is used. Otherwise, import the `[ServerTransferStateModule](../platform-server/servertransferstatemodule)` module to make the `[TransferState](transferstate)` available. The values in the store are serialized/deserialized using JSON.stringify/JSON.parse. So only boolean, number, string, null and non-class objects will be serialized and deserialized in a non-lossy manner. Properties ---------- | Property | Description | | --- | --- | | `isEmpty: boolean` | Read-Only Indicates whether the state is empty. | Methods ------- | get() | | --- | | Get the value corresponding to a key. Return `defaultValue` if key is not found. | | `get<T>(key: StateKey<T>, defaultValue: T): T` Parameters | | | | | --- | --- | --- | | `key` | `[StateKey](statekey)<T>` | | | `defaultValue` | `T` | | Returns `T` | | set() | | --- | | Set the value corresponding to a key. | | `set<T>(key: StateKey<T>, value: T): void` Parameters | | | | | --- | --- | --- | | `key` | `[StateKey](statekey)<T>` | | | `value` | `T` | | Returns `void` | | remove() | | --- | | Remove a key from the store. | | `remove<T>(key: StateKey<T>): void` Parameters | | | | | --- | --- | --- | | `key` | `[StateKey](statekey)<T>` | | Returns `void` | | hasKey() | | --- | | Test whether a key exists in the store. | | `hasKey<T>(key: StateKey<T>)` Parameters | | | | | --- | --- | --- | | `key` | `[StateKey](statekey)<T>` | | | | onSerialize() | | --- | | Register a callback to provide the value for a key when `toJson` is called. | | `onSerialize<T>(key: StateKey<T>, callback: () => T): void` Parameters | | | | | --- | --- | --- | | `key` | `[StateKey](statekey)<T>` | | | `callback` | `() => T` | | Returns `void` | | toJson() | | --- | | Serialize the current state of the store to JSON. | | `toJson(): string` Parameters There are no parameters. Returns `string` | angular platformBrowserTesting platformBrowserTesting ====================== `const` Platform for testing ### `const platformBrowserTesting: (extraProviders?: StaticProvider[]) => PlatformRef;` angular BrowserTestingModule BrowserTestingModule ==================== `ngmodule` NgModule for testing. ``` class BrowserTestingModule { } ``` Providers --------- | Provider | | --- | | ``` { provide: APP_ID, useValue: 'a' } ``` | | ``` { provide: NgZone, useFactory: createNgZone } ``` | | ``` (ENABLE_MOCK_PLATFORM_LOCATION ? [{ provide: PlatformLocation, useClass: MockPlatformLocation }] : []) ``` | angular ANIMATION_MODULE_TYPE ANIMATION\_MODULE\_TYPE ======================= `const` A [DI token](../../../guide/glossary#di-token "DI token definition") that indicates which animations module has been loaded. ### `const ANIMATION_MODULE_TYPE: InjectionToken<"NoopAnimations" | "BrowserAnimations">;` angular provideNoopAnimations provideNoopAnimations ===================== `function` Returns the set of [dependency-injection providers](../../../guide/glossary#provider) to disable animations in an application. See [animations guide](../../../guide/animations) to learn more about animations in Angular. ### `provideNoopAnimations(): Provider[]` ###### Parameters There are no parameters. ###### Returns `[Provider](../../core/provider)[]` Usage notes ----------- The function is useful when you want to bootstrap an application using the `[bootstrapApplication](../bootstrapapplication)` function, but you need to disable animations (for example, when running tests). ``` bootstrapApplication(RootComponent, { providers: [ provideNoopAnimations() ] }); ``` angular NoopAnimationsModule NoopAnimationsModule ==================== `ngmodule` A null player that must be imported to allow disabling of animations. ``` class NoopAnimationsModule { } ``` Providers --------- | Provider | | --- | | ``` BROWSER_NOOP_ANIMATIONS_PROVIDERS ``` | angular BrowserAnimationsModuleConfig BrowserAnimationsModuleConfig ============================= `interface` Object used to configure the behavior of [`BrowserAnimationsModule`](browseranimationsmodule) ``` interface BrowserAnimationsModuleConfig { disableAnimations?: boolean } ``` Properties ---------- | Property | Description | | --- | --- | | `disableAnimations?: boolean` | Whether animations should be disabled. Passing this is identical to providing the `[NoopAnimationsModule](noopanimationsmodule)`, but it can be controlled based on a runtime value. | angular provideAnimations provideAnimations ================= `function` Returns the set of [dependency-injection providers](../../../guide/glossary#provider) to enable animations in an application. See [animations guide](../../../guide/animations) to learn more about animations in Angular. ### `provideAnimations(): Provider[]` ###### Parameters There are no parameters. ###### Returns `[Provider](../../core/provider)[]` Usage notes ----------- The function is useful when you want to enable animations in an application bootstrapped using the `[bootstrapApplication](../bootstrapapplication)` function. In this scenario there is no need to import the `[BrowserAnimationsModule](browseranimationsmodule)` NgModule at all, just add providers returned by this function to the `providers` list as show below. ``` bootstrapApplication(RootComponent, { providers: [ provideAnimations() ] }); ``` angular BrowserAnimationsModule BrowserAnimationsModule ======================= `ngmodule` Exports `[BrowserModule](../browsermodule)` with additional [dependency-injection providers](../../../guide/glossary#provider) for use with animations. See [Animations](../../../guide/animations). ``` class BrowserAnimationsModule { static withConfig(config: BrowserAnimationsModuleConfig): ModuleWithProviders<BrowserAnimationsModule> } ``` Static methods -------------- | withConfig() | | --- | | Configures the module based on the specified object. See also:* `[BrowserAnimationsModuleConfig](browseranimationsmoduleconfig)` | | `static withConfig(config: BrowserAnimationsModuleConfig): ModuleWithProviders<BrowserAnimationsModule>` Parameters | | | | | --- | --- | --- | | `config` | `[BrowserAnimationsModuleConfig](browseranimationsmoduleconfig)` | Object used to configure the behavior of the `[BrowserAnimationsModule](browseranimationsmodule)`. | Returns `[ModuleWithProviders](../../core/modulewithproviders)<[BrowserAnimationsModule](browseranimationsmodule)>` | | Usage Notes When registering the `[BrowserAnimationsModule](browseranimationsmodule)`, you can use the `withConfig` function as follows: ``` @NgModule({ imports: [BrowserAnimationsModule.withConfig(config)] }) class MyNgModule {} ``` | Providers --------- | Provider | | --- | | ``` BROWSER_ANIMATIONS_PROVIDERS ``` |
programming_docs
angular IsActiveMatchOptions IsActiveMatchOptions ==================== `interface` A set of options which specify how to determine if a `[UrlTree](urltree)` is active, given the `[UrlTree](urltree)` for the current router state. ``` interface IsActiveMatchOptions { matrixParams: 'exact' | 'subset' | 'ignored' queryParams: 'exact' | 'subset' | 'ignored' paths: 'exact' | 'subset' fragment: 'exact' | 'ignored' } ``` See also -------- * Router.isActive Properties ---------- | Property | Description | | --- | --- | | `matrixParams: 'exact' | 'subset' | 'ignored'` | Defines the strategy for comparing the matrix parameters of two `[UrlTree](urltree)`s. The matrix parameter matching is dependent on the strategy for matching the segments. That is, if the `paths` option is set to `'subset'`, only the matrix parameters of the matching segments will be compared.* `'exact'`: Requires that matching segments also have exact matrix parameter matches. * `'subset'`: The matching segments in the router's active `[UrlTree](urltree)` may contain extra matrix parameters, but those that exist in the `[UrlTree](urltree)` in question must match. * `'ignored'`: When comparing `[UrlTree](urltree)`s, matrix params will be ignored. | | `queryParams: 'exact' | 'subset' | 'ignored'` | Defines the strategy for comparing the query parameters of two `[UrlTree](urltree)`s.* `'exact'`: the query parameters must match exactly. * `'subset'`: the active `[UrlTree](urltree)` may contain extra parameters, but must match the key and value of any that exist in the `[UrlTree](urltree)` in question. * `'ignored'`: When comparing `[UrlTree](urltree)`s, query params will be ignored. | | `paths: 'exact' | 'subset'` | Defines the strategy for comparing the `[UrlSegment](urlsegment)`s of the `[UrlTree](urltree)`s.* `'exact'`: all segments in each `[UrlTree](urltree)` must match. * `'subset'`: a `[UrlTree](urltree)` will be determined to be active if it is a subtree of the active route. That is, the active route may contain extra segments, but must at least have all the segments of the `[UrlTree](urltree)` in question. | | `fragment: 'exact' | 'ignored'` | * `'exact'`: indicates that the `[UrlTree](urltree)` fragments must be equal. * `'ignored'`: the fragments will not be compared when determining if a `[UrlTree](urltree)` is active. | angular withHashLocation withHashLocation ================ `function` Provides the location strategy that uses the URL fragment instead of the history API. ### `withHashLocation(): RouterConfigurationFeature` ###### Parameters There are no parameters. ###### Returns `[RouterConfigurationFeature](routerconfigurationfeature)`: A set of providers for use with `[provideRouter](providerouter)`. See also -------- * `[provideRouter](providerouter)` * `[HashLocationStrategy](../common/hashlocationstrategy)` Usage notes ----------- Basic example of how you can use the hash location option: ``` const appRoutes: Routes = []; bootstrapApplication(AppComponent, { providers: [ provideRouter(appRoutes, withHashLocation()) ] } ); ``` angular NavigationSkipped NavigationSkipped ================= `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An event triggered when a navigation is skipped. This can happen for a couple reasons including onSameUrlHandling is set to `ignore` and the navigation URL is not different than the current state. ``` class NavigationSkipped extends RouterEvent { constructor(id: number, url: string, reason: string, code?: NavigationSkippedCode) type: EventType.NavigationSkipped reason: string code?: NavigationSkippedCode // inherited from router/RouterEvent constructor(id: number, url: string) id: number url: string } ``` Constructor ----------- | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `constructor(id: number, url: string, reason: string, code?: NavigationSkippedCode)` Parameters | | | | | --- | --- | --- | | `id` | `number` | | | `url` | `string` | | | `reason` | `string` | A description of why the navigation was skipped. For debug purposes only. Use `code` instead for a stable skipped reason that can be used in production. | | `code` | `[NavigationSkippedCode](navigationskippedcode)` | A code to indicate why the navigation was skipped. This code is stable for the reason and can be relied on whereas the `reason` string could change and should not be used in production. Optional. Default is `undefined`. | | Properties ---------- | Property | Description | | --- | --- | | `type: [EventType.NavigationSkipped](eventtype#NavigationSkipped)` | Read-Only | | `reason: string` | Declared in Constructor A description of why the navigation was skipped. For debug purposes only. Use `code` instead for a stable skipped reason that can be used in production. | | `code?: [NavigationSkippedCode](navigationskippedcode)` | Read-Only Declared in Constructor A code to indicate why the navigation was skipped. This code is stable for the reason and can be relied on whereas the `reason` string could change and should not be used in production. | angular RouterConfigOptions RouterConfigOptions =================== `interface` Extra configuration options that can be used with the `[withRouterConfig](withrouterconfig)` function. ``` interface RouterConfigOptions { canceledNavigationResolution?: 'replace' | 'computed' onSameUrlNavigation?: OnSameUrlNavigation paramsInheritanceStrategy?: 'emptyOnly' | 'always' urlUpdateStrategy?: 'deferred' | 'eager' } ``` Child interfaces ---------------- * `[ExtraOptions](extraoptions)` Properties ---------- | Property | Description | | --- | --- | | `canceledNavigationResolution?: 'replace' | 'computed'` | Configures how the Router attempts to restore state when a navigation is cancelled. 'replace' - Always uses `location.replaceState` to set the browser state to the state of the router before the navigation started. This means that if the URL of the browser is updated *before* the navigation is canceled, the Router will simply replace the item in history rather than trying to restore to the previous location in the session history. This happens most frequently with `urlUpdateStrategy: 'eager'` and navigations with the browser back/forward buttons. 'computed' - Will attempt to return to the same index in the session history that corresponds to the Angular route when the navigation gets cancelled. For example, if the browser back button is clicked and the navigation is cancelled, the Router will trigger a forward navigation and vice versa. Note: the 'computed' option is incompatible with any `[UrlHandlingStrategy](urlhandlingstrategy)` which only handles a portion of the URL because the history restoration navigates to the previous place in the browser history rather than simply resetting a portion of the URL. The default value is `replace` when not set. | | `onSameUrlNavigation?: [OnSameUrlNavigation](onsameurlnavigation)` | Configures the default for handling a navigation request to the current URL. If unset, the `[Router](router)` will use `'ignore'`. See also:* `[OnSameUrlNavigation](onsameurlnavigation)` | | `paramsInheritanceStrategy?: 'emptyOnly' | 'always'` | Defines how the router merges parameters, data, and resolved data from parent to child routes. By default ('emptyOnly'), inherits parent parameters only for path-less or component-less routes. Set to 'always' to enable unconditional inheritance of parent parameters. Note that when dealing with matrix parameters, "parent" refers to the parent `[Route](route)` config which does not necessarily mean the "URL segment to the left". When the `[Route](route)` `path` contains multiple segments, the matrix parameters must appear on the last segment. For example, matrix parameters for `{path: 'a/b', component: MyComp}` should appear as `a/b;foo=bar` and not `a;foo=bar/b`. | | `urlUpdateStrategy?: 'deferred' | 'eager'` | Defines when the router updates the browser URL. By default ('deferred'), update after successful navigation. Set to 'eager' if prefer to update the URL at the beginning of navigation. Updating the URL early allows you to handle a failure of navigation by showing an error message with the URL that failed. | angular ROUTES ROUTES ====== `const` The [DI token](../../guide/glossary/index#di-token) for a router configuration. [See more...](routes#description) ### `const ROUTES: InjectionToken<Route[][]>;` #### Description `[ROUTES](routes)` is a low level API for router configuration via dependency injection. We recommend that in almost all cases to use higher level APIs such as `[RouterModule.forRoot()](routermodule#forRoot)`, `[provideRouter](providerouter)`, or `[Router.resetConfig()](router#resetConfig)`. angular CanActivateChild CanActivateChild ================ `interface` Interface that a class can implement to be a guard deciding if a child route can be activated. If all guards return `true`, navigation continues. If any guard returns `false`, navigation is cancelled. If any guard returns a `[UrlTree](urltree)`, current navigation is cancelled and a new navigation begins to the `[UrlTree](urltree)` returned from the guard. [See more...](canactivatechild#description) ``` interface CanActivateChild { canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree } ``` Description ----------- The following example implements a `[CanActivateChild](canactivatechild)` function that checks whether the current user has permission to activate the requested child route. ``` class UserToken {} class Permissions { canActivate(user: UserToken, id: string): boolean { return true; } } @Injectable() class CanActivateTeam implements CanActivateChild { constructor(private permissions: Permissions, private currentUser: UserToken) {} canActivateChild( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree { return this.permissions.canActivate(this.currentUser, route.params.id); } } ``` Here, the defined guard function is provided as part of the `[Route](route)` object in the router configuration: ``` @NgModule({ imports: [ RouterModule.forRoot([ { path: 'root', canActivateChild: [CanActivateTeam], children: [ { path: 'team/:id', component: TeamComponent } ] } ]) ], providers: [CanActivateTeam, UserToken, Permissions] }) class AppModule {} ``` You can alternatively provide an in-line function with the `[CanActivateChildFn](canactivatechildfn)` signature: ``` @NgModule({ imports: [ RouterModule.forRoot([ { path: 'root', canActivateChild: [(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => true], children: [ { path: 'team/:id', component: TeamComponent } ] } ]) ], }) class AppModule {} ``` Methods ------- | canActivateChild() | | --- | | `canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree` Parameters | | | | | --- | --- | --- | | `childRoute` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | | `state` | `[RouterStateSnapshot](routerstatesnapshot)` | | Returns `Observable<boolean | [UrlTree](urltree)> | Promise<boolean | [UrlTree](urltree)> | boolean | [UrlTree](urltree)` | angular RouteConfigLoadEnd RouteConfigLoadEnd ================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An event triggered when a route has been lazy loaded. ``` class RouteConfigLoadEnd { constructor(route: Route) type: EventType.RouteConfigLoadEnd route: Route toString(): string } ``` See also -------- * `[RouteConfigLoadStart](routeconfigloadstart)` Constructor ----------- | | | | | | --- | --- | --- | --- | | `constructor(route: Route)` Parameters | | | | | --- | --- | --- | | `route` | `[Route](route)` | | | Properties ---------- | Property | Description | | --- | --- | | `type: [EventType.RouteConfigLoadEnd](eventtype#RouteConfigLoadEnd)` | Read-Only | | `route: [Route](route)` | Declared in Constructor | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | angular createUrlTreeFromSnapshot createUrlTreeFromSnapshot ========================= `function` Creates a `[UrlTree](urltree)` relative to an `[ActivatedRouteSnapshot](activatedroutesnapshot)`. ### `createUrlTreeFromSnapshot(relativeTo: ActivatedRouteSnapshot, commands: any[], queryParams: Params = null, fragment: string = null): UrlTree` ###### Parameters | | | | | --- | --- | --- | | `relativeTo` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | The `[ActivatedRouteSnapshot](activatedroutesnapshot)` to apply the commands to | | `commands` | `any[]` | An array of URL fragments with which to construct the new URL tree. If the path is static, can be the literal URL string. For a dynamic path, pass an array of path segments, followed by the parameters for each segment. The fragments are applied to the one provided in the `relativeTo` parameter. | | `queryParams` | `[Params](params)` | The query parameters for the `[UrlTree](urltree)`. `null` if the `[UrlTree](urltree)` does not have any query parameters. Optional. Default is `null`. | | `fragment` | `string` | The fragment for the `[UrlTree](urltree)`. `null` if the `[UrlTree](urltree)` does not have a fragment. Optional. Default is `null`. | ###### Returns `[UrlTree](urltree)` Usage notes ----------- ``` // create /team/33/user/11 createUrlTreeFromSnapshot(snapshot, ['/team', 33, 'user', 11]); // create /team/33;expand=true/user/11 createUrlTreeFromSnapshot(snapshot, ['/team', 33, {expand: true}, 'user', 11]); // you can collapse static segments like this (this works only with the first passed-in value): createUrlTreeFromSnapshot(snapshot, ['/team/33/user', userId]); // If the first segment can contain slashes, and you do not want the router to split it, // you can do the following: createUrlTreeFromSnapshot(snapshot, [{segmentPath: '/one/two'}]); // create /team/33/(user/11//right:chat) createUrlTreeFromSnapshot(snapshot, ['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}], null, null); // remove the right secondary node createUrlTreeFromSnapshot(snapshot, ['/team', 33, {outlets: {primary: 'user/11', right: null}}]); // For the examples below, assume the current URL is for the `/team/33/user/11` and the `ActivatedRouteSnapshot` points to `user/11`: // navigate to /team/33/user/11/details createUrlTreeFromSnapshot(snapshot, ['details']); // navigate to /team/33/user/22 createUrlTreeFromSnapshot(snapshot, ['../22']); // navigate to /team/44/user/22 createUrlTreeFromSnapshot(snapshot, ['../../team/44/user/22']); ``` angular withDisabledInitialNavigation withDisabledInitialNavigation ============================= `function` Disables initial navigation. [See more...](withdisabledinitialnavigation#description) ### `withDisabledInitialNavigation(): DisabledInitialNavigationFeature` ###### Parameters There are no parameters. ###### Returns `[DisabledInitialNavigationFeature](disabledinitialnavigationfeature)`: A set of providers for use with `[provideRouter](providerouter)`. See also -------- * `[provideRouter](providerouter)` Description ----------- Use if there is a reason to have more control over when the router starts its initial navigation due to some complex initialization logic. Further information is available in the [Usage Notes...](withdisabledinitialnavigation#usage-notes) Usage notes ----------- Basic example of how you can disable initial navigation: ``` const appRoutes: Routes = []; bootstrapApplication(AppComponent, { providers: [ provideRouter(appRoutes, withDisabledInitialNavigation()) ] } ); ``` angular NavigationSkippedCode NavigationSkippedCode ===================== `enum` A code for the `[NavigationSkipped](navigationskipped)` event of the `[Router](router)` to indicate the reason a navigation was skipped. ``` enum NavigationSkippedCode { IgnoredSameUrlNavigation IgnoredByUrlHandlingStrategy } ``` Members ------- | Member | Description | | --- | --- | | `IgnoredSameUrlNavigation` | A navigation was skipped because the navigation URL was the same as the current Router URL. | | `IgnoredByUrlHandlingStrategy` | A navigation was skipped because the configured `[UrlHandlingStrategy](urlhandlingstrategy)` return `false` for both the current Router URL and the target of the navigation. See also:* UrlHandlingStrategy | angular RouterPreloader RouterPreloader =============== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` The preloader optimistically loads all router configurations to make navigations into lazily-loaded sections of the application faster. [See more...](routerpreloader#description) ``` class RouterPreloader implements OnDestroy { setUpPreloading(): void preload(): Observable<any> } ``` Provided in ----------- * ``` 'root' ``` Description ----------- The preloader runs in the background. When the router bootstraps, the preloader starts listening to all navigation events. After every such event, the preloader will check if any configurations can be loaded lazily. If a route is protected by `canLoad` guards, the preloaded will not load it. Methods ------- | setUpPreloading() | | --- | | `setUpPreloading(): void` Parameters There are no parameters. Returns `void` | | preload() | | --- | | `preload(): Observable<any>` Parameters There are no parameters. Returns `Observable<any>` | angular RouterFeatures RouterFeatures ============== `type-alias` A type alias that represents all Router features available for use with `[provideRouter](providerouter)`. Features can be enabled by adding special functions to the `[provideRouter](providerouter)` call. See documentation for each symbol to find corresponding function name. See also `[provideRouter](providerouter)` documentation on how to use those functions. ``` type RouterFeatures = PreloadingFeature | DebugTracingFeature | InitialNavigationFeature | InMemoryScrollingFeature | RouterConfigurationFeature; ``` See also -------- * `[provideRouter](providerouter)` angular InitialNavigationFeature InitialNavigationFeature ======================== `type-alias` A type alias for providers returned by `[withEnabledBlockingInitialNavigation](withenabledblockinginitialnavigation)` or `[withDisabledInitialNavigation](withdisabledinitialnavigation)` functions for use with `[provideRouter](providerouter)`. ``` type InitialNavigationFeature = EnabledBlockingInitialNavigationFeature | DisabledInitialNavigationFeature; ``` See also -------- * `[withEnabledBlockingInitialNavigation](withenabledblockinginitialnavigation)` * `[withDisabledInitialNavigation](withdisabledinitialnavigation)` * `[provideRouter](providerouter)` angular UrlTree UrlTree ======= `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Represents the parsed URL. [See more...](urltree#description) ``` class UrlTree { constructor(root: UrlSegmentGroup = new UrlSegmentGroup([], {}), queryParams: Params = {}, fragment: string = null) root: UrlSegmentGroup queryParams: Params fragment: string | null queryParamMap: ParamMap toString(): string } ``` Description ----------- Since a router state is a tree, and the URL is nothing but a serialized state, the URL is a serialized tree. UrlTree is a data structure that provides a lot of affordances in dealing with URLs Further information is available in the [Usage Notes...](urltree#usage-notes) Constructor ----------- | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `constructor(root: UrlSegmentGroup = new UrlSegmentGroup([], {}), queryParams: Params = {}, fragment: string = null)` Parameters | | | | | --- | --- | --- | | `root` | `[UrlSegmentGroup](urlsegmentgroup)` | The root segment group of the URL tree Optional. Default is `new [UrlSegmentGroup](urlsegmentgroup)([], {})`. | | `queryParams` | `[Params](params)` | The query params of the URL Optional. Default is `{}`. | | `fragment` | `string` | The fragment of the URL Optional. Default is `null`. | | Properties ---------- | Property | Description | | --- | --- | | `root: [UrlSegmentGroup](urlsegmentgroup)` | Declared in Constructor The root segment group of the URL tree | | `queryParams: [Params](params)` | Declared in Constructor The query params of the URL | | `fragment: string | null` | Declared in Constructor The fragment of the URL | | `queryParamMap: [ParamMap](parammap)` | Read-Only | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | Usage notes ----------- ### Example ``` @Component({templateUrl:'template.html'}) class MyComponent { constructor(router: Router) { const tree: UrlTree = router.parseUrl('/team/33/(user/victor//support:help)?debug=true#fragment'); const f = tree.fragment; // return 'fragment' const q = tree.queryParams; // returns {debug: 'true'} const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET]; const s: UrlSegment[] = g.segments; // returns 2 segments 'team' and '33' g.children[PRIMARY_OUTLET].segments; // returns 2 segments 'user' and 'victor' g.children['support'].segments; // return 1 segment 'help' } } ```
programming_docs
angular PRIMARY_OUTLET PRIMARY\_OUTLET =============== `const` The primary routing outlet. ### `const PRIMARY_OUTLET: "primary";` angular CanMatch CanMatch ======== `interface` Interface that a class can implement to be a guard deciding if a `[Route](route)` can be matched. If all guards return `true`, navigation continues and the `[Router](router)` will use the `[Route](route)` during activation. If any guard returns `false`, the `[Route](route)` is skipped for matching and other `[Route](route)` configurations are processed instead. [See more...](canmatch#description) ``` interface CanMatch { canMatch(route: Route, segments: UrlSegment[]): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree } ``` Description ----------- The following example implements a `[CanMatch](canmatch)` function that decides whether the current user has permission to access the users page. ``` class UserToken {} class Permissions { canAccess(user: UserToken, id: string, segments: UrlSegment[]): boolean { return true; } } @Injectable() class CanMatchTeamSection implements CanMatch { constructor(private permissions: Permissions, private currentUser: UserToken) {} canMatch(route: Route, segments: UrlSegment[]): Observable<boolean>|Promise<boolean>|boolean { return this.permissions.canAccess(this.currentUser, route, segments); } } ``` Here, the defined guard function is provided as part of the `[Route](route)` object in the router configuration: ``` @NgModule({ imports: [ RouterModule.forRoot([ { path: 'team/:id', component: TeamComponent, loadChildren: () => import('./team').then(mod => mod.TeamModule), canMatch: [CanMatchTeamSection] }, { path: '**', component: NotFoundComponent } ]) ], providers: [CanMatchTeamSection, UserToken, Permissions] }) class AppModule {} ``` If the `CanMatchTeamSection` were to return `false`, the router would continue navigating to the `team/:id` URL, but would load the `NotFoundComponent` because the `[Route](route)` for `'team/:id'` could not be used for a URL match but the catch-all `**` `[Route](route)` did instead. You can alternatively provide an in-line function with the `[CanMatchFn](canmatchfn)` signature: ``` @NgModule({ imports: [ RouterModule.forRoot([ { path: 'team/:id', component: TeamComponent, loadChildren: () => import('./team').then(mod => mod.TeamModule), canMatch: [(route: Route, segments: UrlSegment[]) => true] }, { path: '**', component: NotFoundComponent } ]) ], }) class AppModule {} ``` Methods ------- | canMatch() | | --- | | `canMatch(route: Route, segments: UrlSegment[]): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree` Parameters | | | | | --- | --- | --- | | `route` | `[Route](route)` | | | `segments` | `[UrlSegment](urlsegment)[]` | | Returns `Observable<boolean | [UrlTree](urltree)> | Promise<boolean | [UrlTree](urltree)> | boolean | [UrlTree](urltree)` | angular ExtraOptions ExtraOptions ============ `interface` A set of configuration options for a router module, provided in the `forRoot()` method. ``` interface ExtraOptions extends InMemoryScrollingOptions, RouterConfigOptions { enableTracing?: boolean useHash?: boolean initialNavigation?: InitialNavigation errorHandler?: ErrorHandler preloadingStrategy?: any scrollOffset?: [...] malformedUriErrorHandler?: (error: URIError, urlSerializer: UrlSerializer, url: string) => UrlTree // inherited from router/InMemoryScrollingOptions anchorScrolling?: 'disabled' | 'enabled' scrollPositionRestoration?: 'disabled' | 'enabled' | 'top' // inherited from router/RouterConfigOptions canceledNavigationResolution?: 'replace' | 'computed' onSameUrlNavigation?: OnSameUrlNavigation paramsInheritanceStrategy?: 'emptyOnly' | 'always' urlUpdateStrategy?: 'deferred' | 'eager' } ``` See also -------- * `forRoot()` Properties ---------- | Property | Description | | --- | --- | | `enableTracing?: boolean` | When true, log all internal navigation events to the console. Use for debugging. | | `useHash?: boolean` | When true, enable the location strategy that uses the URL fragment instead of the history API. | | `initialNavigation?: [InitialNavigation](initialnavigation)` | One of `enabled`, `enabledBlocking`, `enabledNonBlocking` or `disabled`. When set to `enabled` or `enabledBlocking`, the initial navigation starts before the root component is created. The bootstrap is blocked until the initial navigation is complete. This value is required for [server-side rendering](../../guide/universal) to work. When set to `enabledNonBlocking`, the initial navigation starts after the root component has been created. The bootstrap is not blocked on the completion of the initial navigation. When set to `disabled`, the initial navigation is not performed. The location listener is set up before the root component gets created. Use if there is a reason to have more control over when the router starts its initial navigation due to some complex initialization logic. | | `errorHandler?: [ErrorHandler](../core/errorhandler)` | A custom error handler for failed navigations. If the handler returns a value, the navigation Promise is resolved with this value. If the handler throws an exception, the navigation Promise is rejected with the exception. | | `preloadingStrategy?: any` | Configures a preloading strategy. One of `[PreloadAllModules](preloadallmodules)` or `[NoPreloading](nopreloading)` (the default). | | `scrollOffset?: [ number, number ] | (() => [ number, number ])` | Configures the scroll offset the router will use when scrolling to an element. When given a tuple with x and y position value, the router uses that offset each time it scrolls. When given a function, the router invokes the function every time it restores scroll position. | | `malformedUriErrorHandler?: (error: URIError, urlSerializer: [UrlSerializer](urlserializer), url: string) => [UrlTree](urltree)` | A custom handler for malformed URI errors. The handler is invoked when `encodedURI` contains invalid character sequences. The default implementation is to redirect to the root URL, dropping any path or parameter information. The function takes three parameters:* `'URIError'` - Error thrown when parsing a bad URL. * `'[UrlSerializer](urlserializer)'` - UrlSerializer that’s configured with the router. * `'url'` - The malformed URL that caused the URIError | angular UrlSerializer UrlSerializer ============= `class` Serializes and deserializes a URL string into a URL tree. [See more...](urlserializer#description) ``` abstract class UrlSerializer { abstract parse(url: string): UrlTree abstract serialize(tree: UrlTree): string } ``` Subclasses ---------- * `[DefaultUrlSerializer](defaulturlserializer)` Provided in ----------- * ``` 'root' ``` Description ----------- The url serialization strategy is customizable. You can make all URLs case insensitive by providing a custom UrlSerializer. See `[DefaultUrlSerializer](defaulturlserializer)` for an example of a URL serializer. Methods ------- | parse() | | --- | | Parse a url into a `[UrlTree](urltree)` | | `abstract parse(url: string): UrlTree` Parameters | | | | | --- | --- | --- | | `url` | `string` | | Returns `[UrlTree](urltree)` | | serialize() | | --- | | Converts a `[UrlTree](urltree)` into a url | | `abstract serialize(tree: UrlTree): string` Parameters | | | | | --- | --- | --- | | `tree` | `[UrlTree](urltree)` | | Returns `string` | angular NavigationCancel NavigationCancel ================ `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An event triggered when a navigation is canceled, directly or indirectly. This can happen for several reasons including when a route guard returns `false` or initiates a redirect by returning a `[UrlTree](urltree)`. ``` class NavigationCancel extends RouterEvent { constructor(id: number, url: string, reason: string, code?: NavigationCancellationCode) type: EventType.NavigationCancel reason: string code?: NavigationCancellationCode toString(): string // inherited from router/RouterEvent constructor(id: number, url: string) id: number url: string } ``` See also -------- * `[NavigationStart](navigationstart)` * `[NavigationEnd](navigationend)` * `[NavigationError](navigationerror)` Constructor ----------- | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `constructor(id: number, url: string, reason: string, code?: NavigationCancellationCode)` Parameters | | | | | --- | --- | --- | | `id` | `number` | | | `url` | `string` | | | `reason` | `string` | A description of why the navigation was cancelled. For debug purposes only. Use `code` instead for a stable cancellation reason that can be used in production. | | `code` | `[NavigationCancellationCode](navigationcancellationcode)` | A code to indicate why the navigation was canceled. This cancellation code is stable for the reason and can be relied on whereas the `reason` string could change and should not be used in production. Optional. Default is `undefined`. | | Properties ---------- | Property | Description | | --- | --- | | `type: [EventType.NavigationCancel](eventtype#NavigationCancel)` | Read-Only | | `reason: string` | Declared in Constructor A description of why the navigation was cancelled. For debug purposes only. Use `code` instead for a stable cancellation reason that can be used in production. | | `code?: [NavigationCancellationCode](navigationcancellationcode)` | Read-Only Declared in Constructor A code to indicate why the navigation was canceled. This cancellation code is stable for the reason and can be relied on whereas the `reason` string could change and should not be used in production. | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | angular RouteReuseStrategy RouteReuseStrategy ================== `class` Provides a way to customize when activated routes get reused. ``` abstract class RouteReuseStrategy { abstract shouldDetach(route: ActivatedRouteSnapshot): boolean abstract store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void abstract shouldAttach(route: ActivatedRouteSnapshot): boolean abstract retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null abstract shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean } ``` Subclasses ---------- * `[BaseRouteReuseStrategy](baseroutereusestrategy)` Provided in ----------- * ``` 'root' ``` Methods ------- | shouldDetach() | | --- | | Determines if this route (and its subtree) should be detached to be reused later | | `abstract shouldDetach(route: ActivatedRouteSnapshot): boolean` Parameters | | | | | --- | --- | --- | | `route` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | Returns `boolean` | | store() | | --- | | Stores the detached route. | | `abstract store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void` Parameters | | | | | --- | --- | --- | | `route` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | | `handle` | `[DetachedRouteHandle](detachedroutehandle)` | | Returns `void` | | Storing a `null` value should erase the previously stored value. | | shouldAttach() | | --- | | Determines if this route (and its subtree) should be reattached | | `abstract shouldAttach(route: ActivatedRouteSnapshot): boolean` Parameters | | | | | --- | --- | --- | | `route` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | Returns `boolean` | | retrieve() | | --- | | Retrieves the previously stored route | | `abstract retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null` Parameters | | | | | --- | --- | --- | | `route` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | Returns `[DetachedRouteHandle](detachedroutehandle) | null` | | shouldReuseRoute() | | --- | | Determines if a route should be reused | | `abstract shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean` Parameters | | | | | --- | --- | --- | | `future` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | | `curr` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | Returns `boolean` | angular CanDeactivate CanDeactivate ============= `interface` Interface that a class can implement to be a guard deciding if a route can be deactivated. If all guards return `true`, navigation continues. If any guard returns `false`, navigation is cancelled. If any guard returns a `[UrlTree](urltree)`, current navigation is cancelled and a new navigation begins to the `[UrlTree](urltree)` returned from the guard. [See more...](candeactivate#description) ``` interface CanDeactivate<T> { canDeactivate(component: T, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree } ``` Description ----------- The following example implements a `[CanDeactivate](candeactivate)` function that checks whether the current user has permission to deactivate the requested route. ``` class UserToken {} class Permissions { canDeactivate(user: UserToken, id: string): boolean { return true; } } ``` Here, the defined guard function is provided as part of the `[Route](route)` object in the router configuration: ``` @Injectable() class CanDeactivateTeam implements CanDeactivate<TeamComponent> { constructor(private permissions: Permissions, private currentUser: UserToken) {} canDeactivate( component: TeamComponent, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState: RouterStateSnapshot ): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree { return this.permissions.canDeactivate(this.currentUser, route.params.id); } } @NgModule({ imports: [ RouterModule.forRoot([ { path: 'team/:id', component: TeamComponent, canDeactivate: [CanDeactivateTeam] } ]) ], providers: [CanDeactivateTeam, UserToken, Permissions] }) class AppModule {} ``` You can alternatively provide an in-line function with the `[CanDeactivateFn](candeactivatefn)` signature: ``` @NgModule({ imports: [ RouterModule.forRoot([ { path: 'team/:id', component: TeamComponent, canDeactivate: [(component: TeamComponent, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState: RouterStateSnapshot) => true] } ]) ], }) class AppModule {} ``` Methods ------- | canDeactivate() | | --- | | `canDeactivate(component: T, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree` Parameters | | | | | --- | --- | --- | | `component` | `T` | | | `currentRoute` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | | `currentState` | `[RouterStateSnapshot](routerstatesnapshot)` | | | `nextState` | `[RouterStateSnapshot](routerstatesnapshot)` | | Returns `Observable<boolean | [UrlTree](urltree)> | Promise<boolean | [UrlTree](urltree)> | boolean | [UrlTree](urltree)` | angular Router Router ====== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A service that provides navigation among views and URL manipulation capabilities. ``` class Router { events: Observable<Event> routerState: RouterState errorHandler: this.options.errorHandler || defaultErrorHandler malformedUriErrorHandler: this.options.malformedUriErrorHandler || defaultMalformedUriErrorHandler navigated: boolean urlHandlingStrategy: inject(UrlHandlingStrategy) routeReuseStrategy: inject(RouteReuseStrategy) titleStrategy?: TitleStrategy onSameUrlNavigation: OnSameUrlNavigation paramsInheritanceStrategy: 'emptyOnly' | 'always' urlUpdateStrategy: 'deferred' | 'eager' canceledNavigationResolution: 'replace' | 'computed' config: Routes url: string initialNavigation(): void setUpLocationChangeListener(): void getCurrentNavigation(): Navigation | null resetConfig(config: Routes): void dispose(): void createUrlTree(commands: any[], navigationExtras: UrlCreationOptions = {}): UrlTree navigateByUrl(url: string | UrlTree, extras: NavigationBehaviorOptions = {...}): Promise<boolean> navigate(commands: any[], extras: NavigationExtras = { skipLocationChange: false }): Promise<boolean> serializeUrl(url: UrlTree): string parseUrl(url: string): UrlTree isActive(url: string | UrlTree, matchOptions: boolean | IsActiveMatchOptions): boolean } ``` See also -------- * `[Route](route)`. * [Routing and Navigation Guide](../../guide/router). Provided in ----------- * [``` RouterModule ```](routermodule) * ``` 'root' ``` Properties ---------- | Property | Description | | --- | --- | | `events: Observable<[Event](event)>` | Read-Only An event stream for routing events. | | `routerState: [RouterState](routerstate)` | Read-Only The current state of routing in this NgModule. | | `errorHandler: this.options.errorHandler || defaultErrorHandler` | A handler for navigation errors in this NgModule. **Deprecated** Subscribe to the `[Router](router)` events and watch for `[NavigationError](navigationerror)` instead. | | `malformedUriErrorHandler: this.options.malformedUriErrorHandler || defaultMalformedUriErrorHandler` | A handler for errors thrown by `Router.parseUrl(url)` when `url` contains an invalid character. The most common case is a `%` sign that's not encoded and is not part of a percent encoded sequence. **Deprecated** Configure this through `RouterModule.forRoot` instead: `RouterModule.forRoot(routes, {malformedUriErrorHandler: myHandler})` See also:* `[RouterModule](routermodule)` | | `navigated: boolean` | True if at least one navigation event has occurred, false otherwise. | | `urlHandlingStrategy: inject([UrlHandlingStrategy](urlhandlingstrategy))` | A strategy for extracting and merging URLs. Used for AngularJS to Angular migrations. **Deprecated** Configure using `providers` instead: `{provide: [UrlHandlingStrategy](urlhandlingstrategy), useClass: MyStrategy}`. | | `routeReuseStrategy: inject([RouteReuseStrategy](routereusestrategy))` | A strategy for re-using routes. **Deprecated** Configure using `providers` instead: `{provide: [RouteReuseStrategy](routereusestrategy), useClass: MyStrategy}`. | | `titleStrategy?: [TitleStrategy](titlestrategy)` | A strategy for setting the title based on the `routerState`. **Deprecated** Configure using `providers` instead: `{provide: [TitleStrategy](titlestrategy), useClass: MyStrategy}`. | | `onSameUrlNavigation: [OnSameUrlNavigation](onsameurlnavigation)` | How to handle a navigation request to the current URL. **Deprecated** Configure this through `[provideRouter](providerouter)` or `RouterModule.forRoot` instead. See also:* `[withRouterConfig](withrouterconfig)` * `[provideRouter](providerouter)` * `[RouterModule](routermodule)` | | `paramsInheritanceStrategy: 'emptyOnly' | 'always'` | How to merge parameters, data, resolved data, and title from parent to child routes. One of:* `'emptyOnly'` : Inherit parent parameters, data, and resolved data for path-less or component-less routes. * `'always'` : Inherit parent parameters, data, and resolved data for all child routes. **Deprecated** Configure this through `[provideRouter](providerouter)` or `RouterModule.forRoot` instead. See also:* `[withRouterConfig](withrouterconfig)` * `[provideRouter](providerouter)` * `[RouterModule](routermodule)` | | `urlUpdateStrategy: 'deferred' | 'eager'` | Determines when the router updates the browser URL. By default (`"deferred"`), updates the browser URL after navigation has finished. Set to `'eager'` to update the browser URL at the beginning of navigation. You can choose to update early so that, if navigation fails, you can show an error message with the URL that failed. **Deprecated** Configure this through `[provideRouter](providerouter)` or `RouterModule.forRoot` instead. See also:* `[withRouterConfig](withrouterconfig)` * `[provideRouter](providerouter)` * `[RouterModule](routermodule)` | | `canceledNavigationResolution: 'replace' | 'computed'` | Configures how the Router attempts to restore state when a navigation is cancelled. 'replace' - Always uses `location.replaceState` to set the browser state to the state of the router before the navigation started. This means that if the URL of the browser is updated *before* the navigation is canceled, the Router will simply replace the item in history rather than trying to restore to the previous location in the session history. This happens most frequently with `urlUpdateStrategy: 'eager'` and navigations with the browser back/forward buttons. 'computed' - Will attempt to return to the same index in the session history that corresponds to the Angular route when the navigation gets cancelled. For example, if the browser back button is clicked and the navigation is cancelled, the Router will trigger a forward navigation and vice versa. Note: the 'computed' option is incompatible with any `[UrlHandlingStrategy](urlhandlingstrategy)` which only handles a portion of the URL because the history restoration navigates to the previous place in the browser history rather than simply resetting a portion of the URL. The default value is `replace`. **Deprecated** Configure this through `[provideRouter](providerouter)` or `RouterModule.forRoot` instead. See also:* `[withRouterConfig](withrouterconfig)` * `[provideRouter](providerouter)` * `[RouterModule](routermodule)` | | `config: [Routes](routes)` | | | `url: string` | Read-Only The current URL. | Methods ------- | initialNavigation() | | --- | | Sets up the location change listener and performs the initial navigation. | | `initialNavigation(): void` Parameters There are no parameters. Returns `void` | | setUpLocationChangeListener() | | --- | | Sets up the location change listener. This listener detects navigations triggered from outside the Router (the browser back/forward buttons, for example) and schedules a corresponding Router navigation so that the correct events, guards, etc. are triggered. | | `setUpLocationChangeListener(): void` Parameters There are no parameters. Returns `void` | | getCurrentNavigation() | | --- | | Returns the current `[Navigation](navigation)` object when the router is navigating, and `null` when idle. | | `getCurrentNavigation(): Navigation | null` Parameters There are no parameters. Returns `[Navigation](navigation) | null` | | resetConfig() | | --- | | Resets the route configuration used for navigation and generating links. | | `resetConfig(config: Routes): void` Parameters | | | | | --- | --- | --- | | `config` | `[Routes](routes)` | The route array for the new configuration. | Returns `void` | | Usage Notes ``` router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ { path: 'simple', component: SimpleCmp }, { path: 'user/:name', component: UserCmp } ]} ]); ``` | | dispose() | | --- | | Disposes of the router. | | `dispose(): void` Parameters There are no parameters. Returns `void` | | createUrlTree() | | --- | | Appends URL segments to the current URL tree to create a new URL tree. | | `createUrlTree(commands: any[], navigationExtras: UrlCreationOptions = {}): UrlTree` Parameters | | | | | --- | --- | --- | | `commands` | `any[]` | An array of URL fragments with which to construct the new URL tree. If the path is static, can be the literal URL string. For a dynamic path, pass an array of path segments, followed by the parameters for each segment. The fragments are applied to the current URL tree or the one provided in the `relativeTo` property of the options object, if supplied. | | `navigationExtras` | `[UrlCreationOptions](urlcreationoptions)` | Options that control the navigation strategy. Optional. Default is `{}`. | Returns `[UrlTree](urltree)`: The new URL tree. | | Usage Notes ``` // create /team/33/user/11 router.createUrlTree(['/team', 33, 'user', 11]); // create /team/33;expand=true/user/11 router.createUrlTree(['/team', 33, {expand: true}, 'user', 11]); // you can collapse static segments like this (this works only with the first passed-in value): router.createUrlTree(['/team/33/user', userId]); // If the first segment can contain slashes, and you do not want the router to split it, // you can do the following: router.createUrlTree([{segmentPath: '/one/two'}]); // create /team/33/(user/11//right:chat) router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}]); // remove the right secondary node router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: null}}]); // assuming the current url is `/team/33/user/11` and the route points to `user/11` // navigate to /team/33/user/11/details router.createUrlTree(['details'], {relativeTo: route}); // navigate to /team/33/user/22 router.createUrlTree(['../22'], {relativeTo: route}); // navigate to /team/44/user/22 router.createUrlTree(['../../team/44/user/22'], {relativeTo: route}); Note that a value of `null` or `undefined` for `relativeTo` indicates that the tree should be created relative to the root. ``` | | navigateByUrl() | | --- | | Navigates to a view using an absolute route path. See also:* [Routing and Navigation guide](../../guide/router) | | `navigateByUrl(url: string | UrlTree, extras: NavigationBehaviorOptions = { skipLocationChange: false }): Promise<boolean>` Parameters | | | | | --- | --- | --- | | `url` | `string | [UrlTree](urltree)` | An absolute path for a defined route. The function does not apply any delta to the current URL. | | `extras` | `[NavigationBehaviorOptions](navigationbehavioroptions)` | An object containing properties that modify the navigation strategy. Optional. Default is `{ skipLocationChange: false }`. | Returns `Promise<boolean>`: A Promise that resolves to 'true' when navigation succeeds, to 'false' when navigation fails, or is rejected on error. | | Usage Notes The following calls request navigation to an absolute path. ``` router.navigateByUrl("/team/33/user/11"); // Navigate without updating the URL router.navigateByUrl("/team/33/user/11", { skipLocationChange: true }); ``` | | navigate() | | --- | | Navigate based on the provided array of commands and a starting point. If no starting route is provided, the navigation is absolute. See also:* [Routing and Navigation guide](../../guide/router) | | `navigate(commands: any[], extras: NavigationExtras = { skipLocationChange: false }): Promise<boolean>` Parameters | | | | | --- | --- | --- | | `commands` | `any[]` | An array of URL fragments with which to construct the target URL. If the path is static, can be the literal URL string. For a dynamic path, pass an array of path segments, followed by the parameters for each segment. The fragments are applied to the current URL or the one provided in the `relativeTo` property of the options object, if supplied. | | `extras` | `[NavigationExtras](navigationextras)` | An options object that determines how the URL should be constructed or interpreted. Optional. Default is `{ skipLocationChange: false }`. | Returns `Promise<boolean>`: A Promise that resolves to `true` when navigation succeeds, to `false` when navigation fails, or is rejected on error. | | Usage Notes The following calls request navigation to a dynamic route path relative to the current URL. ``` router.navigate(['team', 33, 'user', 11], {relativeTo: route}); // Navigate without updating the URL, overriding the default behavior router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true}); ``` | | serializeUrl() | | --- | | Serializes a `[UrlTree](urltree)` into a string | | `serializeUrl(url: UrlTree): string` Parameters | | | | | --- | --- | --- | | `url` | `[UrlTree](urltree)` | | Returns `string` | | parseUrl() | | --- | | Parses a string into a `[UrlTree](urltree)` | | `parseUrl(url: string): UrlTree` Parameters | | | | | --- | --- | --- | | `url` | `string` | | Returns `[UrlTree](urltree)` | | isActive() | | --- | | 3 overloads... Show All Hide All Overload #1 Returns whether the url is activated. `isActive(url: string | UrlTree, exact: boolean): boolean` **Deprecated** Use `[IsActiveMatchOptions](isactivematchoptions)` instead. * The equivalent `[IsActiveMatchOptions](isactivematchoptions)` for `true` is `{paths: 'exact', queryParams: 'exact', fragment: 'ignored', matrixParams: 'ignored'}`. * The equivalent for `false` is `{paths: 'subset', queryParams: 'subset', fragment: 'ignored', matrixParams: 'ignored'}`. Parameters | | | | | --- | --- | --- | | `url` | `string | [UrlTree](urltree)` | | | `exact` | `boolean` | | Returns `boolean` Overload #2 Returns whether the url is activated. `isActive(url: string | UrlTree, matchOptions: IsActiveMatchOptions): boolean` Parameters | | | | | --- | --- | --- | | `url` | `string | [UrlTree](urltree)` | | | `matchOptions` | `[IsActiveMatchOptions](isactivematchoptions)` | | Returns `boolean` Overload #3 `isActive(url: string | UrlTree, matchOptions: boolean | IsActiveMatchOptions): boolean` Parameters | | | | | --- | --- | --- | | `url` | `string | [UrlTree](urltree)` | | | `matchOptions` | `boolean | [IsActiveMatchOptions](isactivematchoptions)` | | Returns `boolean` |
programming_docs
angular RouterOutletContract RouterOutletContract ==================== `interface` An interface that defines the contract for developing a component outlet for the `[Router](router)`. [See more...](routeroutletcontract#description) ``` interface RouterOutletContract { isActivated: boolean component: Object | null activatedRouteData: Data activatedRoute: ActivatedRoute | null activateEvents?: EventEmitter<unknown> deactivateEvents?: EventEmitter<unknown> attachEvents?: EventEmitter<unknown> detachEvents?: EventEmitter<unknown> activateWith(activatedRoute: ActivatedRoute, environmentInjector: EnvironmentInjector): void deactivate(): void detach(): ComponentRef<unknown> attach(ref: ComponentRef<unknown>, activatedRoute: ActivatedRoute): void } ``` Class implementations --------------------- * `[RouterOutlet](routeroutlet)` See also -------- * `[ChildrenOutletContexts](childrenoutletcontexts)` Description ----------- An outlet acts as a placeholder that Angular dynamically fills based on the current router state. A router outlet should register itself with the `[Router](router)` via `[ChildrenOutletContexts](childrenoutletcontexts)#onChildOutletCreated` and unregister with `[ChildrenOutletContexts](childrenoutletcontexts)#onChildOutletDestroyed`. When the `[Router](router)` identifies a matched `[Route](route)`, it looks for a registered outlet in the `[ChildrenOutletContexts](childrenoutletcontexts)` and activates it. Properties ---------- | Property | Description | | --- | --- | | `isActivated: boolean` | Whether the given outlet is activated. An outlet is considered "activated" if it has an active component. | | `component: Object | null` | The instance of the activated component or `null` if the outlet is not activated. | | `activatedRouteData: [Data](data)` | The `[Data](data)` of the `[ActivatedRoute](activatedroute)` snapshot. | | `activatedRoute: [ActivatedRoute](activatedroute) | null` | The `[ActivatedRoute](activatedroute)` for the outlet or `null` if the outlet is not activated. | | `activateEvents?: [EventEmitter](../core/eventemitter)<unknown>` | Emits an activate event when a new component is instantiated | | `deactivateEvents?: [EventEmitter](../core/eventemitter)<unknown>` | Emits a deactivate event when a component is destroyed. | | `attachEvents?: [EventEmitter](../core/eventemitter)<unknown>` | Emits an attached component instance when the `[RouteReuseStrategy](routereusestrategy)` instructs to re-attach a previously detached subtree. | | `detachEvents?: [EventEmitter](../core/eventemitter)<unknown>` | Emits a detached component instance when the `[RouteReuseStrategy](routereusestrategy)` instructs to detach the subtree. | Methods ------- | activateWith() | | --- | | Called by the `[Router](router)` when the outlet should activate (create a component). | | `activateWith(activatedRoute: ActivatedRoute, environmentInjector: EnvironmentInjector): void` Parameters | | | | | --- | --- | --- | | `activatedRoute` | `[ActivatedRoute](activatedroute)` | | | `environmentInjector` | `[EnvironmentInjector](../core/environmentinjector)` | | Returns `void` | | `activateWith(activatedRoute: ActivatedRoute, resolver: ComponentFactoryResolver): void` **Deprecated** Passing a resolver to retrieve a component factory is not required and is deprecated since v14. Parameters | | | | | --- | --- | --- | | `activatedRoute` | `[ActivatedRoute](activatedroute)` | | | `resolver` | `[ComponentFactoryResolver](../core/componentfactoryresolver)` | | Returns `void` | | deactivate() | | --- | | A request to destroy the currently activated component. | | `deactivate(): void` Parameters There are no parameters. Returns `void` | | When a `[RouteReuseStrategy](routereusestrategy)` indicates that an `[ActivatedRoute](activatedroute)` should be removed but stored for later re-use rather than destroyed, the `[Router](router)` will call `detach` instead. | | detach() | | --- | | Called when the `[RouteReuseStrategy](routereusestrategy)` instructs to detach the subtree. | | `detach(): ComponentRef<unknown>` Parameters There are no parameters. Returns `[ComponentRef](../core/componentref)<unknown>` | | This is similar to `deactivate`, but the activated component should *not* be destroyed. Instead, it is returned so that it can be reattached later via the `attach` method. | | attach() | | --- | | Called when the `[RouteReuseStrategy](routereusestrategy)` instructs to re-attach a previously detached subtree. | | `attach(ref: ComponentRef<unknown>, activatedRoute: ActivatedRoute): void` Parameters | | | | | --- | --- | --- | | `ref` | `[ComponentRef](../core/componentref)<unknown>` | | | `activatedRoute` | `[ActivatedRoute](activatedroute)` | | Returns `void` | angular CanActivateFn CanActivateFn ============= `type-alias` The signature of a function used as a `canActivate` guard on a `[Route](route)`. ``` type CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree; ``` See also -------- * `[CanActivate](canactivate)` * `[Route](route)` angular CanActivateChildFn CanActivateChildFn ================== `type-alias` The signature of a function used as a `canActivateChild` guard on a `[Route](route)`. ``` type CanActivateChildFn = (childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot) => Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree; ``` See also -------- * `[CanActivateChild](canactivatechild)` * `[Route](route)` angular RouterHashLocationFeature RouterHashLocationFeature ========================= `type-alias` A type alias for providers returned by `[withHashLocation](withhashlocation)` for use with `[provideRouter](providerouter)`. ``` type RouterHashLocationFeature = RouterFeature<RouterFeatureKind.RouterHashLocationFeature>; ``` See also -------- * `[withHashLocation](withhashlocation)` * `[provideRouter](providerouter)` angular DefaultExport DefaultExport ============= `interface` An ES Module object with a default export of the given type. ``` interface DefaultExport<T> { default: T } ``` See also -------- * `[Route](route)#loadComponent` * `[LoadChildrenCallback](loadchildrencallback)` Properties ---------- | Property | Description | | --- | --- | | `default: T` | Default exports are bound under the name `"default"`, per the ES Module spec: <https://tc39.es/ecma262/#table-export-forms-mapping-to-exportentry-records> | angular NavigationError NavigationError =============== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An event triggered when a navigation fails due to an unexpected error. ``` class NavigationError extends RouterEvent { constructor(id: number, url: string, error: any, target?: RouterStateSnapshot) type: EventType.NavigationError error: any target?: RouterStateSnapshot toString(): string // inherited from router/RouterEvent constructor(id: number, url: string) id: number url: string } ``` See also -------- * `[NavigationStart](navigationstart)` * `[NavigationEnd](navigationend)` * `[NavigationCancel](navigationcancel)` Constructor ----------- | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `constructor(id: number, url: string, error: any, target?: RouterStateSnapshot)` Parameters | | | | | --- | --- | --- | | `id` | `number` | | | `url` | `string` | | | `error` | `any` | | | `target` | `[RouterStateSnapshot](routerstatesnapshot)` | The target of the navigation when the error occurred. Note that this can be `undefined` because an error could have occurred before the `[RouterStateSnapshot](routerstatesnapshot)` was created for the navigation. Optional. Default is `undefined`. | | Properties ---------- | Property | Description | | --- | --- | | `type: [EventType.NavigationError](eventtype#NavigationError)` | Read-Only | | `error: any` | Declared in Constructor | | `target?: [RouterStateSnapshot](routerstatesnapshot)` | Read-Only The target of the navigation when the error occurred. Note that this can be `undefined` because an error could have occurred before the `[RouterStateSnapshot](routerstatesnapshot)` was created for the navigation. | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | angular RouteConfigLoadStart RouteConfigLoadStart ==================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An event triggered before lazy loading a route configuration. ``` class RouteConfigLoadStart { constructor(route: Route) type: EventType.RouteConfigLoadStart route: Route toString(): string } ``` See also -------- * `[RouteConfigLoadEnd](routeconfigloadend)` Constructor ----------- | | | | | | --- | --- | --- | --- | | `constructor(route: Route)` Parameters | | | | | --- | --- | --- | | `route` | `[Route](route)` | | | Properties ---------- | Property | Description | | --- | --- | | `type: [EventType.RouteConfigLoadStart](eventtype#RouteConfigLoadStart)` | Read-Only | | `route: [Route](route)` | Declared in Constructor | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | angular NavigationEnd NavigationEnd ============= `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An event triggered when a navigation ends successfully. ``` class NavigationEnd extends RouterEvent { constructor(id: number, url: string, urlAfterRedirects: string) type: EventType.NavigationEnd urlAfterRedirects: string toString(): string // inherited from router/RouterEvent constructor(id: number, url: string) id: number url: string } ``` See also -------- * `[NavigationStart](navigationstart)` * `[NavigationCancel](navigationcancel)` * `[NavigationError](navigationerror)` Constructor ----------- | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `constructor(id: number, url: string, urlAfterRedirects: string)` Parameters | | | | | --- | --- | --- | | `id` | `number` | | | `url` | `string` | | | `urlAfterRedirects` | `string` | | | Properties ---------- | Property | Description | | --- | --- | | `type: [EventType.NavigationEnd](eventtype#NavigationEnd)` | Read-Only | | `urlAfterRedirects: string` | Declared in Constructor | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | angular UrlSegmentGroup UrlSegmentGroup =============== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Represents the parsed URL segment group. [See more...](urlsegmentgroup#description) ``` class UrlSegmentGroup { constructor(segments: UrlSegment[], children: { [key: string]: UrlSegmentGroup; }) parent: UrlSegmentGroup | null segments: UrlSegment[] children: {...} numberOfChildren: number hasChildren(): boolean toString(): string } ``` Description ----------- See `[UrlTree](urltree)` for more information. Constructor ----------- | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | | `constructor(segments: UrlSegment[], children: { [key: string]: UrlSegmentGroup; })` Parameters | | | | | --- | --- | --- | | `segments` | `[UrlSegment](urlsegment)[]` | The URL segments of this group. See `[UrlSegment](urlsegment)` for more information | | `children` | `object` | The list of children of this group | | Properties ---------- | Property | Description | | --- | --- | | `parent: [UrlSegmentGroup](urlsegmentgroup) | null` | The parent node in the url tree | | `segments: [UrlSegment](urlsegment)[]` | Declared in Constructor The URL segments of this group. See `[UrlSegment](urlsegment)` for more information | | `children: { [key: string]: [UrlSegmentGroup](urlsegmentgroup); }` | Declared in Constructor The list of children of this group | | `numberOfChildren: number` | Read-Only Number of child segments | Methods ------- | hasChildren() | | --- | | Whether the segment has child segments | | `hasChildren(): boolean` Parameters There are no parameters. Returns `boolean` | | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | angular TitleStrategy TitleStrategy ============= `class` Provides a strategy for setting the page title after a router navigation. [See more...](titlestrategy#description) ``` abstract class TitleStrategy { abstract updateTitle(snapshot: RouterStateSnapshot): void buildTitle(snapshot: RouterStateSnapshot): string | undefined getResolvedTitleForRoute(snapshot: ActivatedRouteSnapshot) } ``` Subclasses ---------- * `[DefaultTitleStrategy](defaulttitlestrategy)` See also -------- * [Page title guide](../../guide/router#setting-the-page-title) Provided in ----------- * ``` 'root' ``` Description ----------- The built-in implementation traverses the router state snapshot and finds the deepest primary outlet with `title` property. Given the `[Routes](routes)` below, navigating to `/base/child(popup:aux)` would result in the document title being set to "child". ``` [ {path: 'base', title: 'base', children: [ {path: 'child', title: 'child'}, ], {path: 'aux', outlet: 'popup', title: 'popupTitle'} ] ``` This class can be used as a base class for custom title strategies. That is, you can create your own class that extends the `[TitleStrategy](titlestrategy)`. Note that in the above example, the `title` from the named outlet is never used. However, a custom strategy might be implemented to incorporate titles in named outlets. Methods ------- | updateTitle() | | --- | | Performs the application title update. | | `abstract updateTitle(snapshot: RouterStateSnapshot): void` Parameters | | | | | --- | --- | --- | | `snapshot` | `[RouterStateSnapshot](routerstatesnapshot)` | | Returns `void` | | buildTitle() | | --- | | `buildTitle(snapshot: RouterStateSnapshot): string | undefined` Parameters | | | | | --- | --- | --- | | `snapshot` | `[RouterStateSnapshot](routerstatesnapshot)` | | Returns `string | undefined`: The `title` of the deepest primary route. | | getResolvedTitleForRoute() | | --- | | Given an `[ActivatedRouteSnapshot](activatedroutesnapshot)`, returns the final value of the `[Route.title](route#title)` property, which can either be a static string or a resolved value. | | `getResolvedTitleForRoute(snapshot: ActivatedRouteSnapshot)` Parameters | | | | | --- | --- | --- | | `snapshot` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | | angular ActivationStart ActivationStart =============== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An event triggered at the start of the activation part of the Resolve phase of routing. ``` class ActivationStart { constructor(snapshot: ActivatedRouteSnapshot) type: EventType.ActivationStart snapshot: ActivatedRouteSnapshot toString(): string } ``` See also -------- * `[ActivationEnd](activationend)` * `[ResolveStart](resolvestart)` Constructor ----------- | | | | | | --- | --- | --- | --- | | `constructor(snapshot: ActivatedRouteSnapshot)` Parameters | | | | | --- | --- | --- | | `snapshot` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | | Properties ---------- | Property | Description | | --- | --- | | `type: [EventType.ActivationStart](eventtype#ActivationStart)` | Read-Only | | `snapshot: [ActivatedRouteSnapshot](activatedroutesnapshot)` | Declared in Constructor | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | angular Route Route ===== `interface` A configuration object that defines a single route. A set of routes are collected in a `[Routes](routes)` array to define a `[Router](router)` configuration. The router attempts to match segments of a given URL against each route, using the configuration options defined in this object. [See more...](route#description) ``` interface Route { title?: string | Type<Resolve<string>> | ResolveFn<string> path?: string pathMatch?: 'prefix' | 'full' matcher?: UrlMatcher component?: Type<any> loadComponent?: () => Type<unknown> | Observable<Type<unknown> | DefaultExport<Type<unknown>>> | Promise<Type<unknown> | DefaultExport<Type<unknown>>> redirectTo?: string outlet?: string canActivate?: Array<CanActivateFn | any> canMatch?: Array<Type<CanMatch> | InjectionToken<CanMatchFn> | CanMatchFn> canActivateChild?: Array<CanActivateChildFn | any> canDeactivate?: Array<CanDeactivateFn<any> | any> canLoad?: Array<CanLoadFn | any> data?: Data resolve?: ResolveData children?: Routes loadChildren?: LoadChildren runGuardsAndResolvers?: RunGuardsAndResolvers providers?: Array<Provider | EnvironmentProviders> } ``` Description ----------- Supports static, parameterized, redirect, and wildcard routes, as well as custom route data and resolve methods. For detailed usage information, see the [Routing Guide](../../guide/router). Further information is available in the [Usage Notes...](route#usage-notes) Properties ---------- | Property | Description | | --- | --- | | `title?: string | [Type](../core/type)<[Resolve](resolve)<string>> | [ResolveFn](resolvefn)<string>` | Used to define a page title for the route. This can be a static string or an `[Injectable](../core/injectable)` that implements `[Resolve](resolve)`. See also:* `PageTitleStrategy` | | `path?: string` | The path to match against. Cannot be used together with a custom `matcher` function. A URL string that uses router matching notation. Can be a wild card (`**`) that matches any URL (see Usage Notes below). Default is "/" (the root path). | | `pathMatch?: 'prefix' | 'full'` | The path-matching strategy, one of 'prefix' or 'full'. Default is 'prefix'. By default, the router checks URL elements from the left to see if the URL matches a given path and stops when there is a config match. Importantly there must still be a config match for each segment of the URL. For example, '/team/11/user' matches the prefix 'team/:id' if one of the route's children matches the segment 'user'. That is, the URL '/team/11/user' matches the config `{path: 'team/:id', children: [{path: ':user', component: User}]}` but does not match when there are no children as in `{path: 'team/:id', component: Team}`. The path-match strategy 'full' matches against the entire URL. It is important to do this when redirecting empty-path routes. Otherwise, because an empty path is a prefix of any URL, the router would apply the redirect even when navigating to the redirect destination, creating an endless loop. | | `matcher?: [UrlMatcher](urlmatcher)` | A custom URL-matching function. Cannot be used together with `path`. | | `component?: [Type](../core/type)<any>` | The component to instantiate when the path matches. Can be empty if child routes specify components. | | `loadComponent?: () => [Type](../core/type)<unknown> | Observable<[Type](../core/type)<unknown> | [DefaultExport](defaultexport)<[Type](../core/type)<unknown>>> | Promise<[Type](../core/type)<unknown> | [DefaultExport](defaultexport)<[Type](../core/type)<unknown>>>` | An object specifying a lazy-loaded component. | | `redirectTo?: string` | A URL to redirect to when the path matches. Absolute if the URL begins with a slash (/), otherwise relative to the path URL. Note that no further redirects are evaluated after an absolute redirect. When not present, router does not redirect. | | `outlet?: string` | Name of a `[RouterOutlet](routeroutlet)` object where the component can be placed when the path matches. | | `canActivate?: Array<[CanActivateFn](canactivatefn) | any>` | An array of `[CanActivateFn](canactivatefn)` or DI tokens used to look up `[CanActivate](canactivate)()` handlers, in order to determine if the current user is allowed to activate the component. By default, any user can activate. When using a function rather than DI tokens, the function can call `inject` to get any required dependencies. This `inject` call must be done in a synchronous context. | | `canMatch?: Array<[Type](../core/type)<[CanMatch](canmatch)> | [InjectionToken](../core/injectiontoken)<[CanMatchFn](canmatchfn)> | [CanMatchFn](canmatchfn)>` | An array of `[CanMatchFn](canmatchfn)` or DI tokens used to look up `[CanMatch](canmatch)()` handlers, in order to determine if the current user is allowed to match the `[Route](route)`. By default, any route can match. When using a function rather than DI tokens, the function can call `inject` to get any required dependencies. This `inject` call must be done in a synchronous context. | | `canActivateChild?: Array<[CanActivateChildFn](canactivatechildfn) | any>` | An array of `[CanActivateChildFn](canactivatechildfn)` or DI tokens used to look up `[CanActivateChild](canactivatechild)()` handlers, in order to determine if the current user is allowed to activate a child of the component. By default, any user can activate a child. When using a function rather than DI tokens, the function can call `inject` to get any required dependencies. This `inject` call must be done in a synchronous context. | | `canDeactivate?: Array<[CanDeactivateFn](candeactivatefn)<any> | any>` | An array of `[CanDeactivateFn](candeactivatefn)` or DI tokens used to look up `[CanDeactivate](candeactivate)()` handlers, in order to determine if the current user is allowed to deactivate the component. By default, any user can deactivate. When using a function rather than DI tokens, the function can call `inject` to get any required dependencies. This `inject` call must be done in a synchronous context. | | `canLoad?: Array<[CanLoadFn](canloadfn) | any>` | An array of `[CanLoadFn](canloadfn)` or DI tokens used to look up `[CanLoad](canload)()` handlers, in order to determine if the current user is allowed to load the component. By default, any user can load. When using a function rather than DI tokens, the function can call `inject` to get any required dependencies. This `inject` call must be done in a synchronous context. **Deprecated** Use `canMatch` instead | | `data?: [Data](data)` | Additional developer-defined data provided to the component via `[ActivatedRoute](activatedroute)`. By default, no additional data is passed. | | `resolve?: [ResolveData](resolvedata)` | A map of DI tokens used to look up data resolvers. See `[Resolve](resolve)`. | | `children?: [Routes](routes)` | An array of child `[Route](route)` objects that specifies a nested route configuration. | | `loadChildren?: [LoadChildren](loadchildren)` | An object specifying lazy-loaded child routes. | | `runGuardsAndResolvers?: [RunGuardsAndResolvers](runguardsandresolvers)` | A policy for when to run guards and resolvers on a route. Guards and/or resolvers will always run when a route is activated or deactivated. When a route is unchanged, the default behavior is the same as `paramsChange`. `paramsChange` : Rerun the guards and resolvers when path or path param changes. This does not include query parameters. This option is the default.* `always` : Run on every execution. * `pathParamsChange` : Rerun guards and resolvers when the path params change. This does not compare matrix or query parameters. * `paramsOrQueryParamsChange` : Run when path, matrix, or query parameters change. * `pathParamsOrQueryParamsChange` : Rerun guards and resolvers when the path params change or query params have changed. This does not include matrix parameters. See also:* RunGuardsAndResolvers | | `providers?: Array<[Provider](../core/provider) | [EnvironmentProviders](../core/environmentproviders)>` | A `[Provider](../core/provider)` array to use for this `[Route](route)` and its `children`. The `[Router](router)` will create a new `[EnvironmentInjector](../core/environmentinjector)` for this `[Route](route)` and use it for this `[Route](route)` and its `children`. If this route also has a `loadChildren` function which returns an `[NgModuleRef](../core/ngmoduleref)`, this injector will be used as the parent of the lazy loaded module. | Usage notes ----------- ### Simple Configuration The following route specifies that when navigating to, for example, `/team/11/user/bob`, the router creates the 'Team' component with the 'User' child component in it. ``` [{ path: 'team/:id', component: Team, children: [{ path: 'user/:name', component: User }] }] ``` ### Multiple Outlets The following route creates sibling components with multiple outlets. When navigating to `/team/11(aux:chat/jim)`, the router creates the 'Team' component next to the 'Chat' component. The 'Chat' component is placed into the 'aux' outlet. ``` [{ path: 'team/:id', component: Team }, { path: 'chat/:user', component: Chat outlet: 'aux' }] ``` ### Wild Cards The following route uses wild-card notation to specify a component that is always instantiated regardless of where you navigate to. ``` [{ path: '**', component: WildcardComponent }] ``` ### Redirects The following route uses the `redirectTo` property to ignore a segment of a given URL when looking for a child path. When navigating to '/team/11/legacy/user/jim', the router changes the URL segment '/team/11/legacy/user/jim' to '/team/11/user/jim', and then instantiates the Team component with the User child component in it. ``` [{ path: 'team/:id', component: Team, children: [{ path: 'legacy/user/:name', redirectTo: 'user/:name' }, { path: 'user/:name', component: User }] }] ``` The redirect path can be relative, as shown in this example, or absolute. If we change the `redirectTo` value in the example to the absolute URL segment '/user/:name', the result URL is also absolute, '/user/jim'. ### Empty Path Empty-path route configurations can be used to instantiate components that do not 'consume' any URL segments. In the following configuration, when navigating to `/team/11`, the router instantiates the 'AllUsers' component. ``` [{ path: 'team/:id', component: Team, children: [{ path: '', component: AllUsers }, { path: 'user/:name', component: User }] }] ``` Empty-path routes can have children. In the following example, when navigating to `/team/11/user/jim`, the router instantiates the wrapper component with the user component in it. Note that an empty path route inherits its parent's parameters and data. ``` [{ path: 'team/:id', component: Team, children: [{ path: '', component: WrapperCmp, children: [{ path: 'user/:name', component: User }] }] }] ``` ### Matching Strategy The default path-match strategy is 'prefix', which means that the router checks URL elements from the left to see if the URL matches a specified path. For example, '/team/11/user' matches 'team/:id'. ``` [{ path: '', pathMatch: 'prefix', //default redirectTo: 'main' }, { path: 'main', component: Main }] ``` You can specify the path-match strategy 'full' to make sure that the path covers the whole unconsumed URL. It is important to do this when redirecting empty-path routes. Otherwise, because an empty path is a prefix of any URL, the router would apply the redirect even when navigating to the redirect destination, creating an endless loop. In the following example, supplying the 'full' `pathMatch` strategy ensures that the router applies the redirect if and only if navigating to '/'. ``` [{ path: '', pathMatch: 'full', redirectTo: 'main' }, { path: 'main', component: Main }] ``` ### Componentless Routes You can share parameters between sibling components. For example, suppose that two sibling components should go next to each other, and both of them require an ID parameter. You can accomplish this using a route that does not specify a component at the top level. In the following example, 'MainChild' and 'AuxChild' are siblings. When navigating to 'parent/10/(a//aux:b)', the route instantiates the main child and aux child components next to each other. For this to work, the application component must have the primary and aux outlets defined. ``` [{ path: 'parent/:id', children: [ { path: 'a', component: MainChild }, { path: 'b', component: AuxChild, outlet: 'aux' } ] }] ``` The router merges the parameters, data, and resolve of the componentless parent into the parameters, data, and resolve of the children. This is especially useful when child components are defined with an empty path string, as in the following example. With this configuration, navigating to '/parent/10' creates the main child and aux components. ``` [{ path: 'parent/:id', children: [ { path: '', component: MainChild }, { path: '', component: AuxChild, outlet: 'aux' } ] }] ``` ### Lazy Loading Lazy loading speeds up application load time by splitting the application into multiple bundles and loading them on demand. To use lazy loading, provide the `loadChildren` property in the `[Route](route)` object, instead of the `children` property. Given the following example route, the router will lazy load the associated module on demand using the browser native import system. ``` [{ path: 'lazy', loadChildren: () => import('./lazy-route/lazy.module').then(mod => mod.LazyModule), }]; ```
programming_docs
angular OutletContext OutletContext ============= `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Store contextual information about a `[RouterOutlet](routeroutlet)` ``` class OutletContext { outlet: RouterOutletContract | null route: ActivatedRoute | null resolver: ComponentFactoryResolver | null injector: EnvironmentInjector | null children: ChildrenOutletContexts attachRef: ComponentRef<any> | null } ``` Properties ---------- | Property | Description | | --- | --- | | `outlet: [RouterOutletContract](routeroutletcontract) | null` | | | `route: [ActivatedRoute](activatedroute) | null` | | | `resolver: [ComponentFactoryResolver](../core/componentfactoryresolver) | null` | **Deprecated** Passing a resolver to retrieve a component factory is not required and is deprecated since v14. | | `injector: [EnvironmentInjector](../core/environmentinjector) | null` | | | `children: [ChildrenOutletContexts](childrenoutletcontexts)` | | | `attachRef: [ComponentRef](../core/componentref)<any> | null` | | angular RouterStateSnapshot RouterStateSnapshot =================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Represents the state of the router at a moment in time. [See more...](routerstatesnapshot#description) ``` class RouterStateSnapshot extends Tree<ActivatedRouteSnapshot> { url: string toString(): string } ``` Description ----------- This is a tree of activated route snapshots. Every node in this tree knows about the "consumed" URL segments, the extracted parameters, and the resolved data. The following example shows how a component is initialized with information from the snapshot of the root node's state at the time of creation. ``` @Component({templateUrl:'template.html'}) class MyComponent { constructor(router: Router) { const state: RouterState = router.routerState; const snapshot: RouterStateSnapshot = state.snapshot; const root: ActivatedRouteSnapshot = snapshot.root; const child = root.firstChild; const id: Observable<string> = child.params.map(p => p.id); //... } } ``` Constructor ----------- | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | | `constructor(url: string, root: TreeNode<ActivatedRouteSnapshot>)` Parameters | | | | | --- | --- | --- | | `url` | `string` | The url from which this snapshot was created | | `root` | `TreeNode<[ActivatedRouteSnapshot](activatedroutesnapshot)>` | | | Properties ---------- | Property | Description | | --- | --- | | `url: string` | Declared in Constructor The url from which this snapshot was created | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | angular RoutesRecognized RoutesRecognized ================ `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An event triggered when routes are recognized. ``` class RoutesRecognized extends RouterEvent { constructor(id: number, url: string, urlAfterRedirects: string, state: RouterStateSnapshot) type: EventType.RoutesRecognized urlAfterRedirects: string state: RouterStateSnapshot toString(): string // inherited from router/RouterEvent constructor(id: number, url: string) id: number url: string } ``` Constructor ----------- | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `constructor(id: number, url: string, urlAfterRedirects: string, state: RouterStateSnapshot)` Parameters | | | | | --- | --- | --- | | `id` | `number` | | | `url` | `string` | | | `urlAfterRedirects` | `string` | | | `state` | `[RouterStateSnapshot](routerstatesnapshot)` | | | Properties ---------- | Property | Description | | --- | --- | | `type: [EventType.RoutesRecognized](eventtype#RoutesRecognized)` | Read-Only | | `urlAfterRedirects: string` | Declared in Constructor | | `state: [RouterStateSnapshot](routerstatesnapshot)` | Declared in Constructor | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | angular withEnabledBlockingInitialNavigation withEnabledBlockingInitialNavigation ==================================== `function` Configures initial navigation to start before the root component is created. [See more...](withenabledblockinginitialnavigation#description) ### `withEnabledBlockingInitialNavigation(): EnabledBlockingInitialNavigationFeature` ###### Parameters There are no parameters. ###### Returns `[EnabledBlockingInitialNavigationFeature](enabledblockinginitialnavigationfeature)`: A set of providers for use with `[provideRouter](providerouter)`. See also -------- * `[provideRouter](providerouter)` Description ----------- The bootstrap is blocked until the initial navigation is complete. This value is required for [server-side rendering](../../guide/universal) to work. Further information is available in the [Usage Notes...](withenabledblockinginitialnavigation#usage-notes) Usage notes ----------- Basic example of how you can enable this navigation behavior: ``` const appRoutes: Routes = []; bootstrapApplication(AppComponent, { providers: [ provideRouter(appRoutes, withEnabledBlockingInitialNavigation()) ] } ); ``` angular CanDeactivateFn CanDeactivateFn =============== `type-alias` The signature of a function used as a `canDeactivate` guard on a `[Route](route)`. ``` type CanDeactivateFn<T> = (component: T, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState: RouterStateSnapshot) => Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree; ``` See also -------- * `[CanDeactivate](candeactivate)` * `[Route](route)` angular withInMemoryScrolling withInMemoryScrolling ===================== `function` Enables customizable scrolling behavior for router navigations. ### `withInMemoryScrolling(options: InMemoryScrollingOptions = {}): InMemoryScrollingFeature` ###### Parameters | | | | | --- | --- | --- | | `options` | `[InMemoryScrollingOptions](inmemoryscrollingoptions)` | Set of configuration parameters to customize scrolling behavior, see `[InMemoryScrollingOptions](inmemoryscrollingoptions)` for additional information. Optional. Default is `{}`. | ###### Returns `[InMemoryScrollingFeature](inmemoryscrollingfeature)`: A set of providers for use with `[provideRouter](providerouter)`. See also -------- * `[provideRouter](providerouter)` * `[ViewportScroller](../common/viewportscroller)` Usage notes ----------- Basic example of how you can enable scrolling feature: ``` const appRoutes: Routes = []; bootstrapApplication(AppComponent, { providers: [ provideRouter(appRoutes, withInMemoryScrolling()) ] } ); ``` angular ResolveStart ResolveStart ============ `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An event triggered at the start of the Resolve phase of routing. [See more...](resolvestart#description) ``` class ResolveStart extends RouterEvent { constructor(id: number, url: string, urlAfterRedirects: string, state: RouterStateSnapshot) type: EventType.ResolveStart urlAfterRedirects: string state: RouterStateSnapshot toString(): string // inherited from router/RouterEvent constructor(id: number, url: string) id: number url: string } ``` See also -------- * `[ResolveEnd](resolveend)` Description ----------- Runs in the "resolve" phase whether or not there is anything to resolve. In future, may change to only run when there are things to be resolved. Constructor ----------- | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `constructor(id: number, url: string, urlAfterRedirects: string, state: RouterStateSnapshot)` Parameters | | | | | --- | --- | --- | | `id` | `number` | | | `url` | `string` | | | `urlAfterRedirects` | `string` | | | `state` | `[RouterStateSnapshot](routerstatesnapshot)` | | | Properties ---------- | Property | Description | | --- | --- | | `type: [EventType.ResolveStart](eventtype#ResolveStart)` | Read-Only | | `urlAfterRedirects: string` | Declared in Constructor | | `state: [RouterStateSnapshot](routerstatesnapshot)` | Declared in Constructor | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | angular RouterLink RouterLink ========== `directive` When applied to an element in a template, makes that element a link that initiates navigation to a route. Navigation opens one or more routed components in one or more `<[router-outlet](routeroutlet)>` locations on the page. [See more...](routerlink#description) Exported from ------------- * [``` RouterModule ```](routermodule) Selectors --------- * `[[routerLink](routerlink)]` Properties ---------- | Property | Description | | --- | --- | | `href: string | null` | Represents an `href` attribute value applied to a host element, when a host element is `<a>`. For other tags, the value is `null`. | | `@[Input](../core/input)()target?: string` | Represents the `target` attribute on a host element. This is only used when the host element is an `<a>` tag. | | `@[Input](../core/input)()queryParams?: [Params](params) | null` | Passed to [Router#createUrlTree](router#createUrlTree) as part of the `[UrlCreationOptions](urlcreationoptions)`. See also:* [UrlCreationOptions#queryParams](urlcreationoptions#queryParams) * [Router#createUrlTree](router#createUrlTree) | | `@[Input](../core/input)()fragment?: string` | Passed to [Router#createUrlTree](router#createUrlTree) as part of the `[UrlCreationOptions](urlcreationoptions)`. See also:* [UrlCreationOptions#fragment](urlcreationoptions#fragment) * [Router#createUrlTree](router#createUrlTree) | | `@[Input](../core/input)()queryParamsHandling?: [QueryParamsHandling](queryparamshandling) | null` | Passed to [Router#createUrlTree](router#createUrlTree) as part of the `[UrlCreationOptions](urlcreationoptions)`. See also:* [UrlCreationOptions#queryParamsHandling](urlcreationoptions#queryParamsHandling) * [Router#createUrlTree](router#createUrlTree) | | `@[Input](../core/input)()state?: { [k: string]: any; }` | Passed to [Router#navigateByUrl](router#navigateByUrl) as part of the `[NavigationBehaviorOptions](navigationbehavioroptions)`. See also:* [NavigationBehaviorOptions#state](navigationbehavioroptions#state) * [Router#navigateByUrl](router#navigateByUrl) | | `@[Input](../core/input)()relativeTo?: [ActivatedRoute](activatedroute) | null` | Passed to [Router#createUrlTree](router#createUrlTree) as part of the `[UrlCreationOptions](urlcreationoptions)`. Specify a value here when you do not want to use the default value for `[routerLink](routerlink)`, which is the current activated route. Note that a value of `undefined` here will use the `[routerLink](routerlink)` default. See also:* [UrlCreationOptions#relativeTo](urlcreationoptions#relativeTo) * [Router#createUrlTree](router#createUrlTree) | | `@[Input](../core/input)()preserveFragment: boolean` | Passed to [Router#createUrlTree](router#createUrlTree) as part of the `[UrlCreationOptions](urlcreationoptions)`. See also:* [UrlCreationOptions#preserveFragment](urlcreationoptions#preserveFragment) * [Router#createUrlTree](router#createUrlTree) | | `@[Input](../core/input)()skipLocationChange: boolean` | Passed to [Router#navigateByUrl](router#navigateByUrl) as part of the `[NavigationBehaviorOptions](navigationbehavioroptions)`. See also:* [NavigationBehaviorOptions#skipLocationChange](navigationbehavioroptions#skipLocationChange) * [Router#navigateByUrl](router#navigateByUrl) | | `@[Input](../core/input)()replaceUrl: boolean` | Passed to [Router#navigateByUrl](router#navigateByUrl) as part of the `[NavigationBehaviorOptions](navigationbehavioroptions)`. See also:* [NavigationBehaviorOptions#replaceUrl](navigationbehavioroptions#replaceUrl) * [Router#navigateByUrl](router#navigateByUrl) | | `@[Input](../core/input)()[routerLink](routerlink): string | any[]` | Write-Only Commands to pass to [Router#createUrlTree](router#createUrlTree).* **array**: commands to pass to [Router#createUrlTree](router#createUrlTree). * **string**: shorthand for array of commands with just the string, i.e. `['/route']` * **null|undefined**: effectively disables the `[routerLink](routerlink)` See also:* [Router#createUrlTree](router#createUrlTree) | | `urlTree: [UrlTree](urltree) | null` | Read-Only | Description ----------- Given a route configuration `[{ path: 'user/:name', component: UserCmp }]`, the following creates a static link to the route: `<a [routerLink](routerlink)="/user/bob">link to user component</a>` You can use dynamic values to generate the link. For a dynamic link, pass an array of path segments, followed by the params for each segment. For example, `['/team', teamId, 'user', userName, {details: true}]` generates a link to `/team/11/user/bob;details=true`. Multiple static segments can be merged into one term and combined with dynamic segments. For example, `['/team/11/user', userName, {details: true}]` The input that you provide to the link is treated as a delta to the current URL. For instance, suppose the current URL is `/user/(box//aux:team)`. The link `<a [[routerLink](routerlink)]="['/user/jim']">Jim</a>` creates the URL `/user/(jim//aux:team)`. See [createUrlTree](router#createUrlTree) for more information. You can use absolute or relative paths in a link, set query parameters, control how parameters are handled, and keep a history of navigation states. ### Relative link paths The first segment name can be prepended with `/`, `./`, or `../`. * If the first segment begins with `/`, the router looks up the route from the root of the app. * If the first segment begins with `./`, or doesn't begin with a slash, the router looks in the children of the current activated route. * If the first segment begins with `../`, the router goes up one level in the route tree. ### Setting and handling query params and fragments The following link adds a query parameter and a fragment to the generated URL: ``` <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" fragment="education"> link to user component </a> ``` By default, the directive constructs the new URL using the given query parameters. The example generates the link: `/user/bob?debug=true#education`. You can instruct the directive to handle query parameters differently by specifying the `queryParamsHandling` option in the link. Allowed values are: * `'merge'`: Merge the given `queryParams` into the current query params. * `'preserve'`: Preserve the current query params. For example: ``` <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" queryParamsHandling="merge"> link to user component </a> ``` See [UrlCreationOptions#queryParamsHandling](urlcreationoptions#queryParamsHandling). ### Preserving navigation history You can provide a `state` value to be persisted to the browser's [`History.state` property](https://developer.mozilla.org/en-US/docs/Web/API/History#Properties). For example: ``` <a [routerLink]="['/user/bob']" [state]="{tracingId: 123}"> link to user component </a> ``` Use [Router#getCurrentNavigation](router#getCurrentNavigation) to retrieve a saved navigation-state value. For example, to capture the `tracingId` during the `[NavigationStart](navigationstart)` event: ``` // Get NavigationStart events router.events.pipe(filter(e => e instanceof NavigationStart)).subscribe(e => { const navigation = router.getCurrentNavigation(); tracingService.trace({id: navigation.extras.state.tracingId}); }); ``` angular ActivatedRoute ActivatedRoute ============== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Provides access to information about a route associated with a component that is loaded in an outlet. Use to traverse the `[RouterState](routerstate)` tree and extract information from nodes. [See more...](activatedroute#description) ``` class ActivatedRoute { snapshot: ActivatedRouteSnapshot title: Observable<string | undefined> url: Observable<UrlSegment[]> params: Observable<Params> queryParams: Observable<Params> fragment: Observable<string | null> data: Observable<Data> outlet: string component: Type<any> | null routeConfig: Route | null root: ActivatedRoute parent: ActivatedRoute | null firstChild: ActivatedRoute | null children: ActivatedRoute[] pathFromRoot: ActivatedRoute[] paramMap: Observable<ParamMap> queryParamMap: Observable<ParamMap> toString(): string } ``` See also -------- * [Getting route information](../../guide/router#getting-route-information) Description ----------- The following example shows how to construct a component using information from a currently activated route. Note: the observables in this class only emit when the current and previous values differ based on shallow equality. For example, changing deeply nested properties in resolved `data` will not cause the `[ActivatedRoute.data](activatedroute#data)` `Observable` to emit a new value. ``` import {Component} from '@angular/core'; /* . . . */ import {ActivatedRoute} from '@angular/router'; import {Observable} from 'rxjs'; import {map} from 'rxjs/operators'; /* . . . */ @Component({ /* . . . */ }) export class ActivatedRouteComponent { constructor(route: ActivatedRoute) { const id: Observable<string> = route.params.pipe(map(p => p.id)); const url: Observable<string> = route.url.pipe(map(segments => segments.join(''))); // route.data includes both `data` and `resolve` const user = route.data.pipe(map(d => d.user)); } } ``` Constructor ----------- | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `constructor(url: Observable<UrlSegment[]>, params: Observable<Params>, queryParams: Observable<Params>, fragment: Observable<string>, data: Observable<Data>, outlet: string, component: Type<any>, futureSnapshot: ActivatedRouteSnapshot)` Parameters | | | | | --- | --- | --- | | `url` | `Observable<[UrlSegment](urlsegment)[]>` | An observable of the URL segments matched by this route. | | `params` | `Observable<[Params](params)>` | An observable of the matrix parameters scoped to this route. | | `queryParams` | `Observable<[Params](params)>` | An observable of the query parameters shared by all the routes. | | `fragment` | `Observable<string>` | An observable of the URL fragment shared by all the routes. | | `data` | `Observable<[Data](data)>` | An observable of the static and resolved data of this route. | | `outlet` | `string` | The outlet name of the route, a constant. | | `component` | `[Type](../core/type)<any>` | The component of the route, a constant. | | `futureSnapshot` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | | Properties ---------- | Property | Description | | --- | --- | | `snapshot: [ActivatedRouteSnapshot](activatedroutesnapshot)` | The current snapshot of this route | | `title: Observable<string | undefined>` | Read-Only An Observable of the resolved route title | | `url: Observable<[UrlSegment](urlsegment)[]>` | Declared in Constructor An observable of the URL segments matched by this route. | | `params: Observable<[Params](params)>` | Declared in Constructor An observable of the matrix parameters scoped to this route. | | `queryParams: Observable<[Params](params)>` | Declared in Constructor An observable of the query parameters shared by all the routes. | | `fragment: Observable<string | null>` | Declared in Constructor An observable of the URL fragment shared by all the routes. | | `data: Observable<[Data](data)>` | Declared in Constructor An observable of the static and resolved data of this route. | | `outlet: string` | Declared in Constructor The outlet name of the route, a constant. | | `component: [Type](../core/type)<any> | null` | Declared in Constructor The component of the route, a constant. | | `routeConfig: [Route](route) | null` | Read-Only The configuration used to match this route. | | `root: [ActivatedRoute](activatedroute)` | Read-Only The root of the router state. | | `parent: [ActivatedRoute](activatedroute) | null` | Read-Only The parent of this route in the router state tree. | | `firstChild: [ActivatedRoute](activatedroute) | null` | Read-Only The first child of this route in the router state tree. | | `children: [ActivatedRoute](activatedroute)[]` | Read-Only The children of this route in the router state tree. | | `pathFromRoot: [ActivatedRoute](activatedroute)[]` | Read-Only The path from the root of the router state tree to this route. | | `paramMap: Observable<[ParamMap](parammap)>` | Read-Only An Observable that contains a map of the required and optional parameters specific to the route. The map supports retrieving single and multiple values from the same parameter. | | `queryParamMap: Observable<[ParamMap](parammap)>` | Read-Only An Observable that contains a map of the query parameters available to all routes. The map supports retrieving single and multiple values from the query parameter. | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` |
programming_docs
angular RouterFeature RouterFeature ============= `interface` Helper type to represent a Router feature. ``` interface RouterFeature<FeatureKind extends RouterFeatureKind> { } ``` angular ROUTER_CONFIGURATION ROUTER\_CONFIGURATION ===================== `const` A [DI token](../../guide/glossary/index#di-token) for the router service. ### `const ROUTER_CONFIGURATION: InjectionToken<ExtraOptions>;` angular NavigationExtras NavigationExtras ================ `interface` Options that modify the `[Router](router)` navigation strategy. Supply an object containing any of these properties to a `[Router](router)` navigation function to control how the target URL should be constructed or interpreted. ``` interface NavigationExtras extends UrlCreationOptions, NavigationBehaviorOptions { // inherited from router/UrlCreationOptions relativeTo?: ActivatedRoute | null queryParams?: Params | null fragment?: string queryParamsHandling?: QueryParamsHandling | null preserveFragment?: boolean // inherited from router/NavigationBehaviorOptions onSameUrlNavigation?: Extract<OnSameUrlNavigation, 'reload'> skipLocationChange?: boolean replaceUrl?: boolean state?: {...} } ``` See also -------- * [Router.navigate() method](router#navigate) * [Router.navigateByUrl() method](router#navigatebyurl) * [Router.createUrlTree() method](router#createurltree) * [Routing and Navigation guide](../../guide/router) * UrlCreationOptions * NavigationBehaviorOptions angular RunGuardsAndResolvers RunGuardsAndResolvers ===================== `type-alias` A policy for when to run guards and resolvers on a route. [See more...](runguardsandresolvers#description) ``` type RunGuardsAndResolvers = 'pathParamsChange' | 'pathParamsOrQueryParamsChange' | 'paramsChange' | 'paramsOrQueryParamsChange' | 'always' | ((from: ActivatedRouteSnapshot, to: ActivatedRouteSnapshot) => boolean); ``` See also -------- * [Route.runGuardsAndResolvers](route#runGuardsAndResolvers) Description ----------- Guards and/or resolvers will always run when a route is activated or deactivated. When a route is unchanged, the default behavior is the same as `paramsChange`. `paramsChange` : Rerun the guards and resolvers when path or path param changes. This does not include query parameters. This option is the default. * `always` : Run on every execution. * `pathParamsChange` : Rerun guards and resolvers when the path params change. This does not compare matrix or query parameters. * `paramsOrQueryParamsChange` : Run when path, matrix, or query parameters change. * `pathParamsOrQueryParamsChange` : Rerun guards and resolvers when the path params change or query params have changed. This does not include matrix parameters. angular LoadChildrenCallback LoadChildrenCallback ==================== `type-alias` A function that is called to resolve a collection of lazy-loaded routes. Must be an arrow function of the following form: `() => import('...').then(mod => mod.MODULE)` or `() => import('...').then(mod => mod.ROUTES)` [See more...](loadchildrencallback#description) ``` type LoadChildrenCallback = () => Type<any> | NgModuleFactory<any> | Routes | Observable<Type<any> | Routes | DefaultExport<Type<any>> | DefaultExport<Routes>> | Promise<NgModuleFactory<any> | Type<any> | Routes | DefaultExport<Type<any>> | DefaultExport<Routes>>; ``` Description ----------- For example: ``` [{ path: 'lazy', loadChildren: () => import('./lazy-route/lazy.module').then(mod => mod.LazyModule), }]; ``` or ``` [{ path: 'lazy', loadChildren: () => import('./lazy-route/lazy.routes').then(mod => mod.ROUTES), }]; ``` If the lazy-loaded routes are exported via a `default` export, the `.then` can be omitted: ``` [{ path: 'lazy', loadChildren: () => import('./lazy-route/lazy.routes'), }]; @see [Route.loadChildren](api/router/Route#loadChildren) @publicApi ``` angular Data Data ==== `type-alias` Represents static data associated with a particular route. ``` type Data = { [key: string | symbol]: any; }; ``` See also -------- * `[Route](route)#data` angular RouterConfigurationFeature RouterConfigurationFeature ========================== `type-alias` A type alias for providers returned by `[withRouterConfig](withrouterconfig)` for use with `[provideRouter](providerouter)`. ``` type RouterConfigurationFeature = RouterFeature<RouterFeatureKind.RouterConfigurationFeature>; ``` See also -------- * `[withRouterConfig](withrouterconfig)` * `[provideRouter](providerouter)` angular DetachedRouteHandle DetachedRouteHandle =================== `type-alias` Represents the detached route tree. [See more...](detachedroutehandle#description) ``` type DetachedRouteHandle = {}; ``` Description ----------- This is an opaque value the router will give to a custom route reuse strategy to store and retrieve later on. angular ChildActivationEnd ChildActivationEnd ================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An event triggered at the end of the child-activation part of the Resolve phase of routing. ``` class ChildActivationEnd { constructor(snapshot: ActivatedRouteSnapshot) type: EventType.ChildActivationEnd snapshot: ActivatedRouteSnapshot toString(): string } ``` See also -------- * `[ChildActivationStart](childactivationstart)` * `[ResolveStart](resolvestart)` Constructor ----------- | | | | | | --- | --- | --- | --- | | `constructor(snapshot: ActivatedRouteSnapshot)` Parameters | | | | | --- | --- | --- | | `snapshot` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | | Properties ---------- | Property | Description | | --- | --- | | `type: [EventType.ChildActivationEnd](eventtype#ChildActivationEnd)` | Read-Only | | `snapshot: [ActivatedRouteSnapshot](activatedroutesnapshot)` | Declared in Constructor | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | angular DebugTracingFeature DebugTracingFeature =================== `type-alias` A type alias for providers returned by `[withDebugTracing](withdebugtracing)` for use with `[provideRouter](providerouter)`. ``` type DebugTracingFeature = RouterFeature<RouterFeatureKind.DebugTracingFeature>; ``` See also -------- * `[withDebugTracing](withdebugtracing)` * `[provideRouter](providerouter)` angular ActivationEnd ActivationEnd ============= `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An event triggered at the end of the activation part of the Resolve phase of routing. ``` class ActivationEnd { constructor(snapshot: ActivatedRouteSnapshot) type: EventType.ActivationEnd snapshot: ActivatedRouteSnapshot toString(): string } ``` See also -------- * `[ActivationStart](activationstart)` * `[ResolveStart](resolvestart)` Constructor ----------- | | | | | | --- | --- | --- | --- | | `constructor(snapshot: ActivatedRouteSnapshot)` Parameters | | | | | --- | --- | --- | | `snapshot` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | | Properties ---------- | Property | Description | | --- | --- | | `type: [EventType.ActivationEnd](eventtype#ActivationEnd)` | Read-Only | | `snapshot: [ActivatedRouteSnapshot](activatedroutesnapshot)` | Declared in Constructor | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | angular convertToParamMap convertToParamMap ================= `function` Converts a `[Params](params)` instance to a `[ParamMap](parammap)`. ### `convertToParamMap(params: Params): ParamMap` ###### Parameters | | | | | --- | --- | --- | | `params` | `[Params](params)` | The instance to convert. | ###### Returns `[ParamMap](parammap)`: The new map instance. angular PreloadingFeature PreloadingFeature ================= `type-alias` A type alias that represents a feature which enables preloading in Router. The type is used to describe the return value of the `[withPreloading](withpreloading)` function. ``` type PreloadingFeature = RouterFeature<RouterFeatureKind.PreloadingFeature>; ``` See also -------- * `[withPreloading](withpreloading)` * `[provideRouter](providerouter)` angular RouterLinkWithHref RouterLinkWithHref ================== `directive` When applied to an element in a template, makes that element a link that initiates navigation to a route. Navigation opens one or more routed components in one or more `<[router-outlet](routeroutlet)>` locations on the page. [See more...](routerlinkwithhref#description) Exported from ------------- * [``` RouterModule ```](routermodule) Selectors --------- * `[[routerLink](routerlink)]` Properties ---------- | Property | Description | | --- | --- | | `href: string | null` | Represents an `href` attribute value applied to a host element, when a host element is `<a>`. For other tags, the value is `null`. | | `@[Input](../core/input)()target?: string` | Represents the `target` attribute on a host element. This is only used when the host element is an `<a>` tag. | | `@[Input](../core/input)()queryParams?: [Params](params) | null` | Passed to [Router#createUrlTree](router#createUrlTree) as part of the `[UrlCreationOptions](urlcreationoptions)`. See also:* [UrlCreationOptions#queryParams](urlcreationoptions#queryParams) * [Router#createUrlTree](router#createUrlTree) | | `@[Input](../core/input)()fragment?: string` | Passed to [Router#createUrlTree](router#createUrlTree) as part of the `[UrlCreationOptions](urlcreationoptions)`. See also:* [UrlCreationOptions#fragment](urlcreationoptions#fragment) * [Router#createUrlTree](router#createUrlTree) | | `@[Input](../core/input)()queryParamsHandling?: [QueryParamsHandling](queryparamshandling) | null` | Passed to [Router#createUrlTree](router#createUrlTree) as part of the `[UrlCreationOptions](urlcreationoptions)`. See also:* [UrlCreationOptions#queryParamsHandling](urlcreationoptions#queryParamsHandling) * [Router#createUrlTree](router#createUrlTree) | | `@[Input](../core/input)()state?: { [k: string]: any; }` | Passed to [Router#navigateByUrl](router#navigateByUrl) as part of the `[NavigationBehaviorOptions](navigationbehavioroptions)`. See also:* [NavigationBehaviorOptions#state](navigationbehavioroptions#state) * [Router#navigateByUrl](router#navigateByUrl) | | `@[Input](../core/input)()relativeTo?: [ActivatedRoute](activatedroute) | null` | Passed to [Router#createUrlTree](router#createUrlTree) as part of the `[UrlCreationOptions](urlcreationoptions)`. Specify a value here when you do not want to use the default value for `[routerLink](routerlink)`, which is the current activated route. Note that a value of `undefined` here will use the `[routerLink](routerlink)` default. See also:* [UrlCreationOptions#relativeTo](urlcreationoptions#relativeTo) * [Router#createUrlTree](router#createUrlTree) | | `@[Input](../core/input)()preserveFragment: boolean` | Passed to [Router#createUrlTree](router#createUrlTree) as part of the `[UrlCreationOptions](urlcreationoptions)`. See also:* [UrlCreationOptions#preserveFragment](urlcreationoptions#preserveFragment) * [Router#createUrlTree](router#createUrlTree) | | `@[Input](../core/input)()skipLocationChange: boolean` | Passed to [Router#navigateByUrl](router#navigateByUrl) as part of the `[NavigationBehaviorOptions](navigationbehavioroptions)`. See also:* [NavigationBehaviorOptions#skipLocationChange](navigationbehavioroptions#skipLocationChange) * [Router#navigateByUrl](router#navigateByUrl) | | `@[Input](../core/input)()replaceUrl: boolean` | Passed to [Router#navigateByUrl](router#navigateByUrl) as part of the `[NavigationBehaviorOptions](navigationbehavioroptions)`. See also:* [NavigationBehaviorOptions#replaceUrl](navigationbehavioroptions#replaceUrl) * [Router#navigateByUrl](router#navigateByUrl) | | `@[Input](../core/input)()[routerLink](routerlink): string | any[]` | Write-Only Commands to pass to [Router#createUrlTree](router#createUrlTree).* **array**: commands to pass to [Router#createUrlTree](router#createUrlTree). * **string**: shorthand for array of commands with just the string, i.e. `['/route']` * **null|undefined**: effectively disables the `[routerLink](routerlink)` See also:* [Router#createUrlTree](router#createUrlTree) | | `urlTree: [UrlTree](urltree) | null` | Read-Only | Description ----------- Given a route configuration `[{ path: 'user/:name', component: UserCmp }]`, the following creates a static link to the route: `<a [routerLink](routerlink)="/user/bob">link to user component</a>` You can use dynamic values to generate the link. For a dynamic link, pass an array of path segments, followed by the params for each segment. For example, `['/team', teamId, 'user', userName, {details: true}]` generates a link to `/team/11/user/bob;details=true`. Multiple static segments can be merged into one term and combined with dynamic segments. For example, `['/team/11/user', userName, {details: true}]` The input that you provide to the link is treated as a delta to the current URL. For instance, suppose the current URL is `/user/(box//aux:team)`. The link `<a [[routerLink](routerlink)]="['/user/jim']">Jim</a>` creates the URL `/user/(jim//aux:team)`. See [createUrlTree](router#createUrlTree) for more information. You can use absolute or relative paths in a link, set query parameters, control how parameters are handled, and keep a history of navigation states. ### Relative link paths The first segment name can be prepended with `/`, `./`, or `../`. * If the first segment begins with `/`, the router looks up the route from the root of the app. * If the first segment begins with `./`, or doesn't begin with a slash, the router looks in the children of the current activated route. * If the first segment begins with `../`, the router goes up one level in the route tree. ### Setting and handling query params and fragments The following link adds a query parameter and a fragment to the generated URL: ``` <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" fragment="education"> link to user component </a> ``` By default, the directive constructs the new URL using the given query parameters. The example generates the link: `/user/bob?debug=true#education`. You can instruct the directive to handle query parameters differently by specifying the `queryParamsHandling` option in the link. Allowed values are: * `'merge'`: Merge the given `queryParams` into the current query params. * `'preserve'`: Preserve the current query params. For example: ``` <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" queryParamsHandling="merge"> link to user component </a> ``` See [UrlCreationOptions#queryParamsHandling](urlcreationoptions#queryParamsHandling). ### Preserving navigation history You can provide a `state` value to be persisted to the browser's [`History.state` property](https://developer.mozilla.org/en-US/docs/Web/API/History#Properties). For example: ``` <a [routerLink]="['/user/bob']" [state]="{tracingId: 123}"> link to user component </a> ``` Use [Router#getCurrentNavigation](router#getCurrentNavigation) to retrieve a saved navigation-state value. For example, to capture the `tracingId` during the `[NavigationStart](navigationstart)` event: ``` // Get NavigationStart events router.events.pipe(filter(e => e instanceof NavigationStart)).subscribe(e => { const navigation = router.getCurrentNavigation(); tracingService.trace({id: navigation.extras.state.tracingId}); }); ``` angular ResolveFn ResolveFn ========= `type-alias` Function type definition for a data provider. ``` type ResolveFn<T> = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => Observable<T> | Promise<T> | T; ``` See also -------- * `[Route](route)#resolve`. angular GuardsCheckStart GuardsCheckStart ================ `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An event triggered at the start of the Guard phase of routing. ``` class GuardsCheckStart extends RouterEvent { constructor(id: number, url: string, urlAfterRedirects: string, state: RouterStateSnapshot) type: EventType.GuardsCheckStart urlAfterRedirects: string state: RouterStateSnapshot toString(): string // inherited from router/RouterEvent constructor(id: number, url: string) id: number url: string } ``` See also -------- * `[GuardsCheckEnd](guardscheckend)` Constructor ----------- | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `constructor(id: number, url: string, urlAfterRedirects: string, state: RouterStateSnapshot)` Parameters | | | | | --- | --- | --- | | `id` | `number` | | | `url` | `string` | | | `urlAfterRedirects` | `string` | | | `state` | `[RouterStateSnapshot](routerstatesnapshot)` | | | Properties ---------- | Property | Description | | --- | --- | | `type: [EventType.GuardsCheckStart](eventtype#GuardsCheckStart)` | Read-Only | | `urlAfterRedirects: string` | Declared in Constructor | | `state: [RouterStateSnapshot](routerstatesnapshot)` | Declared in Constructor | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | angular provideRoutes provideRoutes ============= `function` `deprecated` Registers a [DI provider](../../guide/glossary#provider) for a set of routes. **Deprecated:** If necessary, provide routes using the `[ROUTES](routes)` `[InjectionToken](../core/injectiontoken)`. ### `provideRoutes(routes: Routes): Provider[]` **Deprecated** If necessary, provide routes using the `[ROUTES](routes)` `[InjectionToken](../core/injectiontoken)`. ###### Parameters | | | | | --- | --- | --- | | `routes` | `[Routes](routes)` | The route configuration to provide. | ###### Returns `[Provider](../core/provider)[]` See also -------- * `[ROUTES](routes)` Usage notes ----------- ``` @NgModule({ providers: [provideRoutes(ROUTES)] }) class LazyLoadedChildModule {} ``` angular withRouterConfig withRouterConfig ================ `function` Allows to provide extra parameters to configure Router. ### `withRouterConfig(options: RouterConfigOptions): RouterConfigurationFeature` ###### Parameters | | | | | --- | --- | --- | | `options` | `[RouterConfigOptions](routerconfigoptions)` | A set of parameters to configure Router, see `[RouterConfigOptions](routerconfigoptions)` for additional information. | ###### Returns `[RouterConfigurationFeature](routerconfigurationfeature)`: A set of providers for use with `[provideRouter](providerouter)`. See also -------- * `[provideRouter](providerouter)` Usage notes ----------- Basic example of how you can provide extra configuration options: ``` const appRoutes: Routes = []; bootstrapApplication(AppComponent, { providers: [ provideRouter(appRoutes, withRouterConfig({ onSameUrlNavigation: 'reload' })) ] } ); ``` angular @angular/router/upgrade @angular/router/upgrade ======================= `entry-point` Provides support for upgrading routing applications from Angular JS to Angular. Entry point exports ------------------- ### Functions | | | | --- | --- | | `[setUpLocationSync](upgrade/setuplocationsync)` | Sets up a location change listener to trigger `history.pushState`. Works around the problem that `onPopState` does not trigger `history.pushState`. Must be called *after* calling `UpgradeModule.bootstrap`. | ### Types | | | | --- | --- | | `[RouterUpgradeInitializer](upgrade/routerupgradeinitializer)` | Creates an initializer that sets up `ngRoute` integration along with setting up the Angular router. |
programming_docs
angular Event Event ===== `type-alias` Router events that allow you to track the lifecycle of the router. [See more...](event#description) ``` type Event = RouterEvent | NavigationStart | NavigationEnd | NavigationCancel | NavigationError | RoutesRecognized | GuardsCheckStart | GuardsCheckEnd | RouteConfigLoadStart | RouteConfigLoadEnd | ChildActivationStart | ChildActivationEnd | ActivationStart | ActivationEnd | Scroll | ResolveStart | ResolveEnd | NavigationSkipped; ``` Description ----------- The events occur in the following sequence: * [NavigationStart](navigationstart): Navigation starts. * [RouteConfigLoadStart](routeconfigloadstart): Before the router [lazy loads](../../guide/router#lazy-loading) a route configuration. * [RouteConfigLoadEnd](routeconfigloadend): After a route has been lazy loaded. * [RoutesRecognized](routesrecognized): When the router parses the URL and the routes are recognized. * [GuardsCheckStart](guardscheckstart): When the router begins the *guards* phase of routing. * [ChildActivationStart](childactivationstart): When the router begins activating a route's children. * [ActivationStart](activationstart): When the router begins activating a route. * [GuardsCheckEnd](guardscheckend): When the router finishes the *guards* phase of routing successfully. * [ResolveStart](resolvestart): When the router begins the *resolve* phase of routing. * [ResolveEnd](resolveend): When the router finishes the *resolve* phase of routing successfully. * [ChildActivationEnd](childactivationend): When the router finishes activating a route's children. * [ActivationEnd](activationend): When the router finishes activating a route. * [NavigationEnd](navigationend): When navigation ends successfully. * [NavigationCancel](navigationcancel): When navigation is canceled. * [NavigationError](navigationerror): When navigation fails due to an unexpected error. * [Scroll](scroll): When the user scrolls. angular ParamMap ParamMap ======== `interface` A map that provides access to the required and optional parameters specific to a route. The map supports retrieving a single value with `get()` or multiple values with `getAll()`. ``` interface ParamMap { keys: string[] has(name: string): boolean get(name: string): string | null getAll(name: string): string[] } ``` See also -------- * [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) Properties ---------- | Property | Description | | --- | --- | | `keys: string[]` | Read-Only Names of the parameters in the map. | Methods ------- | has() | | --- | | Reports whether the map contains a given parameter. | | `has(name: string): boolean` Parameters | | | | | --- | --- | --- | | `name` | `string` | The parameter name. | Returns `boolean`: True if the map contains the given parameter, false otherwise. | | get() | | --- | | Retrieves a single value for a parameter. | | `get(name: string): string | null` Parameters | | | | | --- | --- | --- | | `name` | `string` | The parameter name. | Returns `string | null`: The parameter's single value, or the first value if the parameter has multiple values, or `null` when there is no such parameter. | | getAll() | | --- | | Retrieves multiple values for a parameter. | | `getAll(name: string): string[]` Parameters | | | | | --- | --- | --- | | `name` | `string` | The parameter name. | Returns `string[]`: An array containing one or more values, or an empty array if there is no such parameter. | angular Params Params ====== `type-alias` A collection of matrix and query URL parameters. ``` type Params = { [key: string]: any; }; ``` See also -------- * `[convertToParamMap](converttoparammap)()` * `[ParamMap](parammap)` angular ActivatedRouteSnapshot ActivatedRouteSnapshot ====================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Contains the information about a route associated with a component loaded in an outlet at a particular moment in time. ActivatedRouteSnapshot can also be used to traverse the router state tree. [See more...](activatedroutesnapshot#description) ``` class ActivatedRouteSnapshot { routeConfig: Route | null title: string | undefined url: UrlSegment[] params: Params queryParams: Params fragment: string | null data: Data outlet: string component: Type<any> | null root: ActivatedRouteSnapshot parent: ActivatedRouteSnapshot | null firstChild: ActivatedRouteSnapshot | null children: ActivatedRouteSnapshot[] pathFromRoot: ActivatedRouteSnapshot[] paramMap: ParamMap queryParamMap: ParamMap toString(): string } ``` Description ----------- The following example initializes a component with route information extracted from the snapshot of the root node at the time of creation. ``` @Component({templateUrl:'./my-component.html'}) class MyComponent { constructor(route: ActivatedRoute) { const id: string = route.snapshot.params.id; const url: string = route.snapshot.url.join(''); const user = route.snapshot.data.user; } } ``` Constructor ----------- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `constructor(url: UrlSegment[], params: Params, queryParams: Params, fragment: string, data: Data, outlet: string, component: Type<any>, routeConfig: Route, urlSegment: UrlSegmentGroup, lastPathIndex: number, resolve: ResolveData)` Parameters | | | | | --- | --- | --- | | `url` | `[UrlSegment](urlsegment)[]` | The URL segments matched by this route | | `params` | `[Params](params)` | The matrix parameters scoped to this route. You can compute all params (or data) in the router state or to get params outside of an activated component by traversing the `[RouterState](routerstate)` tree as in the following example: ``` collectRouteParams(router: Router) { let params = {}; let stack: ActivatedRouteSnapshot[] = [router.routerState.snapshot.root]; while (stack.length > 0) { const route = stack.pop()!; params = {...params, ...route.params}; stack.push(...route.children); } return params; } ``` | | `queryParams` | `[Params](params)` | The query parameters shared by all the routes | | `fragment` | `string` | The URL fragment shared by all the routes | | `data` | `[Data](data)` | The static and resolved data of this route | | `outlet` | `string` | The outlet name of the route | | `component` | `[Type](../core/type)<any>` | The component of the route | | `routeConfig` | `[Route](route)` | | | `urlSegment` | `[UrlSegmentGroup](urlsegmentgroup)` | | | `lastPathIndex` | `number` | | | `resolve` | `[ResolveData](resolvedata)` | | | Properties ---------- | Property | Description | | --- | --- | | `routeConfig: [Route](route) | null` | Read-Only The configuration used to match this route \* | | `title: string | undefined` | Read-Only The resolved route title | | `url: [UrlSegment](urlsegment)[]` | Declared in Constructor The URL segments matched by this route | | `params: [Params](params)` | The matrix parameters scoped to this route. You can compute all params (or data) in the router state or to get params outside of an activated component by traversing the `[RouterState](routerstate)` tree as in the following example: ``` collectRouteParams(router: Router) { let params = {}; let stack: ActivatedRouteSnapshot[] = [router.routerState.snapshot.root]; while (stack.length > 0) { const route = stack.pop()!; params = {...params, ...route.params}; stack.push(...route.children); } return params; } ``` | | `queryParams: [Params](params)` | Declared in Constructor The query parameters shared by all the routes | | `fragment: string | null` | Declared in Constructor The URL fragment shared by all the routes | | `data: [Data](data)` | Declared in Constructor The static and resolved data of this route | | `outlet: string` | Declared in Constructor The outlet name of the route | | `component: [Type](../core/type)<any> | null` | Declared in Constructor The component of the route | | `root: [ActivatedRouteSnapshot](activatedroutesnapshot)` | Read-Only The root of the router state | | `parent: [ActivatedRouteSnapshot](activatedroutesnapshot) | null` | Read-Only The parent of this route in the router state tree | | `firstChild: [ActivatedRouteSnapshot](activatedroutesnapshot) | null` | Read-Only The first child of this route in the router state tree | | `children: [ActivatedRouteSnapshot](activatedroutesnapshot)[]` | Read-Only The children of this route in the router state tree | | `pathFromRoot: [ActivatedRouteSnapshot](activatedroutesnapshot)[]` | Read-Only The path from the root of the router state tree to this route | | `paramMap: [ParamMap](parammap)` | Read-Only | | `queryParamMap: [ParamMap](parammap)` | Read-Only | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | angular InMemoryScrollingFeature InMemoryScrollingFeature ======================== `type-alias` A type alias for providers returned by `[withInMemoryScrolling](withinmemoryscrolling)` for use with `[provideRouter](providerouter)`. ``` type InMemoryScrollingFeature = RouterFeature<RouterFeatureKind.InMemoryScrollingFeature>; ``` See also -------- * `[withInMemoryScrolling](withinmemoryscrolling)` * `[provideRouter](providerouter)` angular NavigationCancellationCode NavigationCancellationCode ========================== `enum` A code for the `[NavigationCancel](navigationcancel)` event of the `[Router](router)` to indicate the reason a navigation failed. ``` enum NavigationCancellationCode { Redirect SupersededByNewNavigation NoDataFromResolver GuardRejected } ``` Members ------- | Member | Description | | --- | --- | | `Redirect` | A navigation failed because a guard returned a `[UrlTree](urltree)` to redirect. | | `SupersededByNewNavigation` | A navigation failed because a more recent navigation started. | | `NoDataFromResolver` | A navigation failed because one of the resolvers completed without emiting a value. | | `GuardRejected` | A navigation failed because a guard returned `false`. | angular UrlMatchResult UrlMatchResult ============== `type-alias` Represents the result of matching URLs with a custom matching function. [See more...](urlmatchresult#description) ``` type UrlMatchResult = { consumed: UrlSegment[]; posParams?: { [name: string]: UrlSegment; }; }; ``` See also -------- * `[UrlMatcher](urlmatcher)()` Description ----------- * `consumed` is an array of the consumed URL segments. * `posParams` is a map of positional parameters. angular DefaultTitleStrategy DefaultTitleStrategy ==================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` The default `[TitleStrategy](titlestrategy)` used by the router that updates the title using the `[Title](../platform-browser/title)` service. ``` class DefaultTitleStrategy extends TitleStrategy { title: Title updateTitle(snapshot: RouterStateSnapshot): void // inherited from router/TitleStrategy abstract updateTitle(snapshot: RouterStateSnapshot): void buildTitle(snapshot: RouterStateSnapshot): string | undefined getResolvedTitleForRoute(snapshot: ActivatedRouteSnapshot) } ``` Provided in ----------- * ``` 'root' ``` Properties ---------- | Property | Description | | --- | --- | | `title: [Title](../platform-browser/title)` | Read-Only | Methods ------- | updateTitle() | | --- | | Sets the title of the browser to the given value. | | `updateTitle(snapshot: RouterStateSnapshot): void` Parameters | | | | | --- | --- | --- | | `snapshot` | `[RouterStateSnapshot](routerstatesnapshot)` | | Returns `void` | angular NoPreloading NoPreloading ============ `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Provides a preloading strategy that does not preload any modules. [See more...](nopreloading#description) ``` class NoPreloading implements PreloadingStrategy { preload(route: Route, fn: () => Observable<any>): Observable<any> } ``` Provided in ----------- * ``` 'root' ``` Description ----------- This strategy is enabled by default. Methods ------- | preload() | | --- | | `preload(route: Route, fn: () => Observable<any>): Observable<any>` Parameters | | | | | --- | --- | --- | | `route` | `[Route](route)` | | | `fn` | `() => Observable<any>` | | Returns `Observable<any>` | angular RouterEvent RouterEvent =========== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Base for events the router goes through, as opposed to events tied to a specific route. Fired one time for any given navigation. [See more...](routerevent#description) ``` class RouterEvent { constructor(id: number, url: string) id: number url: string } ``` Subclasses ---------- * `[GuardsCheckEnd](guardscheckend)` * `[GuardsCheckStart](guardscheckstart)` * `[NavigationCancel](navigationcancel)` * `[NavigationEnd](navigationend)` * `[NavigationError](navigationerror)` * `[NavigationSkipped](navigationskipped)` * `[NavigationStart](navigationstart)` * `[ResolveEnd](resolveend)` * `[ResolveStart](resolvestart)` * `[RoutesRecognized](routesrecognized)` See also -------- * `[Event](event)` * [Router events summary](../../guide/router-reference#router-events) Description ----------- The following code shows how a class subscribes to router events. ``` import {Event, RouterEvent, Router} from '@angular/router'; class MyService { constructor(public router: Router) { router.events.pipe( filter((e: Event): e is RouterEvent => e instanceof RouterEvent) ).subscribe((e: RouterEvent) => { // Do something }); } } ``` Constructor ----------- | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | | `constructor(id: number, url: string)` Parameters | | | | | --- | --- | --- | | `id` | `number` | A unique ID that the router assigns to every router navigation. | | `url` | `string` | The URL that is the destination for this navigation. | | Properties ---------- | Property | Description | | --- | --- | | `id: number` | Declared in Constructor A unique ID that the router assigns to every router navigation. | | `url: string` | Declared in Constructor The URL that is the destination for this navigation. | angular EnabledBlockingInitialNavigationFeature EnabledBlockingInitialNavigationFeature ======================================= `type-alias` A type alias for providers returned by `[withEnabledBlockingInitialNavigation](withenabledblockinginitialnavigation)` for use with `[provideRouter](providerouter)`. ``` type EnabledBlockingInitialNavigationFeature = RouterFeature<RouterFeatureKind.EnabledBlockingInitialNavigationFeature>; ``` See also -------- * `[withEnabledBlockingInitialNavigation](withenabledblockinginitialnavigation)` * `[provideRouter](providerouter)` angular InMemoryScrollingOptions InMemoryScrollingOptions ======================== `interface` Configuration options for the scrolling feature which can be used with `[withInMemoryScrolling](withinmemoryscrolling)` function. ``` interface InMemoryScrollingOptions { anchorScrolling?: 'disabled' | 'enabled' scrollPositionRestoration?: 'disabled' | 'enabled' | 'top' } ``` Child interfaces ---------------- * `[ExtraOptions](extraoptions)` Properties ---------- | Property | Description | | --- | --- | | `anchorScrolling?: 'disabled' | 'enabled'` | When set to 'enabled', scrolls to the anchor element when the URL has a fragment. Anchor scrolling is disabled by default. Anchor scrolling does not happen on 'popstate'. Instead, we restore the position that we stored or scroll to the top. | | `scrollPositionRestoration?: 'disabled' | 'enabled' | 'top'` | Configures if the scroll position needs to be restored when navigating back.* 'disabled'- (Default) Does nothing. Scroll position is maintained on navigation. * 'top'- Sets the scroll position to x = 0, y = 0 on all navigation. * 'enabled'- Restores the previous scroll position on backward navigation, else sets the position to the anchor if one is provided, or sets the scroll position to [0, 0] (forward navigation). This option will be the default in the future. You can implement custom scroll restoration behavior by adapting the enabled behavior as in the following example. ``` class AppComponent { movieData: any; constructor(private router: Router, private viewportScroller: ViewportScroller, changeDetectorRef: ChangeDetectorRef) { router.events.pipe(filter((event: Event): event is Scroll => event instanceof Scroll) ).subscribe(e => { fetch('http://example.com/movies.json').then(response => { this.movieData = response.json(); // update the template with the data before restoring scroll changeDetectorRef.detectChanges(); if (e.position) { viewportScroller.scrollToPosition(e.position); } }); }); } } ``` | angular ChildActivationStart ChildActivationStart ==================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An event triggered at the start of the child-activation part of the Resolve phase of routing. ``` class ChildActivationStart { constructor(snapshot: ActivatedRouteSnapshot) type: EventType.ChildActivationStart snapshot: ActivatedRouteSnapshot toString(): string } ``` See also -------- * `[ChildActivationEnd](childactivationend)` * `[ResolveStart](resolvestart)` Constructor ----------- | | | | | | --- | --- | --- | --- | | `constructor(snapshot: ActivatedRouteSnapshot)` Parameters | | | | | --- | --- | --- | | `snapshot` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | | Properties ---------- | Property | Description | | --- | --- | | `type: [EventType.ChildActivationStart](eventtype#ChildActivationStart)` | Read-Only | | `snapshot: [ActivatedRouteSnapshot](activatedroutesnapshot)` | Declared in Constructor | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | angular PreloadingStrategy PreloadingStrategy ================== `class` Provides a preloading strategy. ``` abstract class PreloadingStrategy { abstract preload(route: Route, fn: () => Observable<any>): Observable<any> } ``` Subclasses ---------- * `[NoPreloading](nopreloading)` * `[PreloadAllModules](preloadallmodules)` Methods ------- | preload() | | --- | | `abstract preload(route: Route, fn: () => Observable<any>): Observable<any>` Parameters | | | | | --- | --- | --- | | `route` | `[Route](route)` | | | `fn` | `() => Observable<any>` | | Returns `Observable<any>` | angular DisabledInitialNavigationFeature DisabledInitialNavigationFeature ================================ `type-alias` A type alias for providers returned by `[withDisabledInitialNavigation](withdisabledinitialnavigation)` for use with `[provideRouter](providerouter)`. ``` type DisabledInitialNavigationFeature = RouterFeature<RouterFeatureKind.DisabledInitialNavigationFeature>; ``` See also -------- * `[withDisabledInitialNavigation](withdisabledinitialnavigation)` * `[provideRouter](providerouter)` angular OnSameUrlNavigation OnSameUrlNavigation =================== `type-alias` How to handle a navigation request to the current URL. One of: [See more...](onsameurlnavigation#description) ``` type OnSameUrlNavigation = 'reload' | 'ignore'; ``` See also -------- * RouteReuseStrategy * RunGuardsAndResolvers * NavigationBehaviorOptions * RouterConfigOptions Description ----------- * `'ignore'` : The router ignores the request it is the same as the current state. * `'reload'` : The router processes the URL even if it is not different from the current state. One example of when you might want this option is if a `canMatch` guard depends on application state and initially rejects navigation to a route. After fixing the state, you want to re-navigate to the same URL so the route with the `canMatch` guard can activate. Note that this only configures whether the Route reprocesses the URL and triggers related action and events like redirects, guards, and resolvers. By default, the router re-uses a component instance when it re-navigates to the same component type without visiting a different component first. This behavior is configured by the `[RouteReuseStrategy](routereusestrategy)`. In order to reload routed components on same url navigation, you need to set `onSameUrlNavigation` to `'reload'` *and* provide a `[RouteReuseStrategy](routereusestrategy)` which returns `false` for `shouldReuseRoute`. Additionally, resolvers and most guards for routes do not run unless the path or path params changed (configured by `runGuardsAndResolvers`).
programming_docs
angular provideRouter provideRouter ============= `function` Sets up providers necessary to enable `[Router](router)` functionality for the application. Allows to configure a set of routes as well as extra features that should be enabled. ### `provideRouter(routes: Routes, ...features: RouterFeatures[]): EnvironmentProviders` ###### Parameters | | | | | --- | --- | --- | | `routes` | `[Routes](routes)` | A set of `[Route](route)`s to use for the application routing table. | | `features` | `[RouterFeatures](routerfeatures)[]` | Optional features to configure additional router behaviors. | ###### Returns `[EnvironmentProviders](../core/environmentproviders)`: A set of providers to setup a Router. See also -------- * `[RouterFeatures](routerfeatures)` Usage notes ----------- Basic example of how you can add a Router to your application: ``` const appRoutes: Routes = []; bootstrapApplication(AppComponent, { providers: [provideRouter(appRoutes)] }); ``` You can also enable optional features in the Router by adding functions from the `[RouterFeatures](routerfeatures)` type: ``` const appRoutes: Routes = []; bootstrapApplication(AppComponent, { providers: [ provideRouter(appRoutes, withDebugTracing(), withRouterConfig({paramsInheritanceStrategy: 'always'})) ] } ); ``` angular CanMatchFn CanMatchFn ========== `type-alias` The signature of a function used as a `[CanMatch](canmatch)` guard on a `[Route](route)`. ``` type CanMatchFn = (route: Route, segments: UrlSegment[]) => Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree; ``` See also -------- * `[CanMatch](canmatch)` * `[Route](route)` angular ROUTER_INITIALIZER ROUTER\_INITIALIZER =================== `const` A [DI token](../../guide/glossary/index#di-token) for the router initializer that is called after the app is bootstrapped. ### `const ROUTER_INITIALIZER: InjectionToken<(compRef: ComponentRef<any>) => void>;` angular CanLoad CanLoad ======= `interface` `deprecated` Interface that a class can implement to be a guard deciding if children can be loaded. If all guards return `true`, navigation continues. If any guard returns `false`, navigation is cancelled. If any guard returns a `[UrlTree](urltree)`, current navigation is cancelled and a new navigation starts to the `[UrlTree](urltree)` returned from the guard. [See more...](canload#description) **Deprecated:** Use `[CanMatch](canmatch)` instead ``` interface CanLoad { canLoad(route: Route, segments: UrlSegment[]): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree } ``` Description ----------- The following example implements a `[CanLoad](canload)` function that decides whether the current user has permission to load requested child routes. ``` class UserToken {} class Permissions { canLoadChildren(user: UserToken, id: string, segments: UrlSegment[]): boolean { return true; } } @Injectable() class CanLoadTeamSection implements CanLoad { constructor(private permissions: Permissions, private currentUser: UserToken) {} canLoad(route: Route, segments: UrlSegment[]): Observable<boolean>|Promise<boolean>|boolean { return this.permissions.canLoadChildren(this.currentUser, route, segments); } } ``` Here, the defined guard function is provided as part of the `[Route](route)` object in the router configuration: ``` @NgModule({ imports: [ RouterModule.forRoot([ { path: 'team/:id', component: TeamComponent, loadChildren: () => import('./team').then(mod => mod.TeamModule), canLoad: [CanLoadTeamSection] } ]) ], providers: [CanLoadTeamSection, UserToken, Permissions] }) class AppModule {} ``` You can alternatively provide an in-line function with the `[CanLoadFn](canloadfn)` signature: ``` @NgModule({ imports: [ RouterModule.forRoot([ { path: 'team/:id', component: TeamComponent, loadChildren: () => import('./team').then(mod => mod.TeamModule), canLoad: [(route: Route, segments: UrlSegment[]) => true] } ]) ], }) class AppModule {} ``` Methods ------- | canLoad() | | --- | | `canLoad(route: Route, segments: UrlSegment[]): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree` Parameters | | | | | --- | --- | --- | | `route` | `[Route](route)` | | | `segments` | `[UrlSegment](urlsegment)[]` | | Returns `Observable<boolean | [UrlTree](urltree)> | Promise<boolean | [UrlTree](urltree)> | boolean | [UrlTree](urltree)` | angular RouterLinkActive RouterLinkActive ================ `directive` Tracks whether the linked route of an element is currently active, and allows you to specify one or more CSS classes to add to the element when the linked route is active. [See more...](routerlinkactive#description) Exported from ------------- * [``` RouterModule ```](routermodule) Selectors --------- * `[[routerLinkActive](routerlinkactive)]` Properties ---------- | Property | Description | | --- | --- | | `links: [QueryList](../core/querylist)<[RouterLink](routerlink)>` | | | `isActive` | Read-Only | | `@[Input](../core/input)()routerLinkActiveOptions: { exact: boolean; } | [IsActiveMatchOptions](isactivematchoptions)` | Options to configure how to determine if the router link is active. These options are passed to the `[Router.isActive()](router#isActive)` function. See also:* Router.isActive | | `@[Input](../core/input)()ariaCurrentWhenActive?: 'page' | 'step' | 'location' | 'date' | 'time' | true | false` | Aria-current attribute to apply when the router link is active. Possible values: `'page'` | `'step'` | `'location'` | `'date'` | `'time'` | `true` | `false`. See also:* [aria-current](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-current) | | `@[Output](../core/output)()isActiveChange: [EventEmitter](../core/eventemitter)<boolean>` | Read-Only You can use the output `isActiveChange` to get notified each time the link becomes active or inactive. Emits: true -> Route is active false -> Route is inactive ``` <a routerLink="/user/bob" routerLinkActive="active-link" (isActiveChange)="this.onRouterLinkActive($event)">Bob</a> ``` | | `@[Input](../core/input)()[routerLinkActive](routerlinkactive): string | string[]` | Write-Only | Template variable references ---------------------------- | Identifier | Usage | | --- | --- | | `[routerLinkActive](routerlinkactive)` | `#myTemplateVar="[routerLinkActive](routerlinkactive)"` | Description ----------- Use this directive to create a visual distinction for elements associated with an active route. For example, the following code highlights the word "Bob" when the router activates the associated route: ``` <a routerLink="/user/bob" routerLinkActive="active-link">Bob</a> ``` Whenever the URL is either '/user' or '/user/bob', the "active-link" class is added to the anchor tag. If the URL changes, the class is removed. You can set more than one class using a space-separated string or an array. For example: ``` <a routerLink="/user/bob" routerLinkActive="class1 class2">Bob</a> <a routerLink="/user/bob" [routerLinkActive]="['class1', 'class2']">Bob</a> ``` To add the classes only when the URL matches the link exactly, add the option `exact: true`: ``` <a routerLink="/user/bob" routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}">Bob</a> ``` To directly check the `isActive` status of the link, assign the `[RouterLinkActive](routerlinkactive)` instance to a template variable. For example, the following checks the status without assigning any CSS classes: ``` <a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive"> Bob {{ rla.isActive ? '(already open)' : ''}} </a> ``` You can apply the `[RouterLinkActive](routerlinkactive)` directive to an ancestor of linked elements. For example, the following sets the active-link class on the `<div>` parent tag when the URL is either '/user/jim' or '/user/bob'. ``` <div routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}"> <a routerLink="/user/jim">Jim</a> <a routerLink="/user/bob">Bob</a> </div> ``` The `[RouterLinkActive](routerlinkactive)` directive can also be used to set the aria-current attribute to provide an alternative distinction for active elements to visually impaired users. For example, the following code adds the 'active' class to the Home Page link when it is indeed active and in such case also sets its aria-current attribute to 'page': ``` <a routerLink="/" routerLinkActive="active" ariaCurrentWhenActive="page">Home Page</a> ``` angular EventType EventType ========= `enum` Identifies the type of a router event. ``` enum EventType { NavigationStart NavigationEnd NavigationCancel NavigationError RoutesRecognized ResolveStart ResolveEnd GuardsCheckStart GuardsCheckEnd RouteConfigLoadStart RouteConfigLoadEnd ChildActivationStart ChildActivationEnd ActivationStart ActivationEnd Scroll NavigationSkipped } ``` Members ------- | Member | Description | | --- | --- | | `[NavigationStart](navigationstart)` | | | `[NavigationEnd](navigationend)` | | | `[NavigationCancel](navigationcancel)` | | | `[NavigationError](navigationerror)` | | | `[RoutesRecognized](routesrecognized)` | | | `[ResolveStart](resolvestart)` | | | `[ResolveEnd](resolveend)` | | | `[GuardsCheckStart](guardscheckstart)` | | | `[GuardsCheckEnd](guardscheckend)` | | | `[RouteConfigLoadStart](routeconfigloadstart)` | | | `[RouteConfigLoadEnd](routeconfigloadend)` | | | `[ChildActivationStart](childactivationstart)` | | | `[ChildActivationEnd](childactivationend)` | | | `[ActivationStart](activationstart)` | | | `[ActivationEnd](activationend)` | | | `[Scroll](scroll)` | | | `[NavigationSkipped](navigationskipped)` | | angular defaultUrlMatcher defaultUrlMatcher ================= `function` Matches the route configuration (`route`) against the actual URL (`segments`). [See more...](defaulturlmatcher#description) ### `defaultUrlMatcher(segments: UrlSegment[], segmentGroup: UrlSegmentGroup, route: Route): UrlMatchResult | null` ###### Parameters | | | | | --- | --- | --- | | `segments` | `[UrlSegment](urlsegment)[]` | The remaining unmatched segments in the current navigation | | `segmentGroup` | `[UrlSegmentGroup](urlsegmentgroup)` | The current segment group being matched | | `route` | `[Route](route)` | The `[Route](route)` to match against. | ###### Returns `[UrlMatchResult](urlmatchresult) | null`: The resulting match information or `null` if the `route` should not match. See also -------- * UrlMatchResult * Route Description ----------- When no matcher is defined on a `[Route](route)`, this is the matcher used by the Router by default. angular UrlCreationOptions UrlCreationOptions ================== `interface` Options that modify the `[Router](router)` URL. Supply an object containing any of these properties to a `[Router](router)` navigation function to control how the target URL should be constructed. ``` interface UrlCreationOptions { relativeTo?: ActivatedRoute | null queryParams?: Params | null fragment?: string queryParamsHandling?: QueryParamsHandling | null preserveFragment?: boolean } ``` Child interfaces ---------------- * `[NavigationExtras](navigationextras)` See also -------- * [Router.navigate() method](router#navigate) * [Router.createUrlTree() method](router#createurltree) * [Routing and Navigation guide](../../guide/router) Properties ---------- | Property | Description | | --- | --- | | `relativeTo?: [ActivatedRoute](activatedroute) | null` | Specifies a root URI to use for relative navigation. For example, consider the following route configuration where the parent route has two children. ``` [{ path: 'parent', component: ParentComponent, children: [{ path: 'list', component: ListComponent },{ path: 'child', component: ChildComponent }] }] ``` The following `go()` function navigates to the `list` route by interpreting the destination URI as relative to the activated `child` route ``` @Component({...}) class ChildComponent { constructor(private router: Router, private route: ActivatedRoute) {} go() { router.navigate(['../list'], { relativeTo: this.route }); } } ``` A value of `null` or `undefined` indicates that the navigation commands should be applied relative to the root. | | `queryParams?: [Params](params) | null` | Sets query parameters to the URL. ``` // Navigate to /results?page=1 router.navigate(['/results'], { queryParams: { page: 1 } }); ``` | | `fragment?: string` | Sets the hash fragment for the URL. ``` // Navigate to /results#top router.navigate(['/results'], { fragment: 'top' }); ``` | | `queryParamsHandling?: [QueryParamsHandling](queryparamshandling) | null` | How to handle query parameters in the router link for the next navigation. One of:* `preserve` : Preserve current parameters. * `merge` : Merge new with current parameters. The "preserve" option discards any new query params: ``` // from /view1?page=1 to/view2?page=1 router.navigate(['/view2'], { queryParams: { page: 2 }, queryParamsHandling: "preserve" }); ``` The "merge" option appends new query params to the params from the current URL: ``` // from /view1?page=1 to/view2?page=1&otherKey=2 router.navigate(['/view2'], { queryParams: { otherKey: 2 }, queryParamsHandling: "merge" }); ``` In case of a key collision between current parameters and those in the `queryParams` object, the new value is used. | | `preserveFragment?: boolean` | When true, preserves the URL fragment for the next navigation ``` // Preserve fragment from /results#top to /view#top router.navigate(['/view'], { preserveFragment: true }); ``` | angular NavigationStart NavigationStart =============== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An event triggered when a navigation starts. ``` class NavigationStart extends RouterEvent { constructor(id: number, url: string, navigationTrigger: NavigationTrigger = 'imperative', restoredState: { [k: string]: any; navigationId: number; } = null) type: EventType.NavigationStart navigationTrigger?: NavigationTrigger restoredState?: {...} toString(): string // inherited from router/RouterEvent constructor(id: number, url: string) id: number url: string } ``` Constructor ----------- | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `constructor(id: number, url: string, navigationTrigger: NavigationTrigger = 'imperative', restoredState: { [k: string]: any; navigationId: number; } = null)` Parameters | | | | | --- | --- | --- | | `id` | `number` | | | `url` | `string` | | | `navigationTrigger` | `NavigationTrigger` | Optional. Default is `'imperative'`. | | `restoredState` | `object` | Optional. Default is `null`. | | Properties ---------- | Property | Description | | --- | --- | | `type: [EventType.NavigationStart](eventtype#NavigationStart)` | Read-Only | | `navigationTrigger?: NavigationTrigger` | Identifies the call or event that triggered the navigation. An `imperative` trigger is a call to `router.navigateByUrl()` or `router.navigate()`. See also:* `[NavigationEnd](navigationend)` * `[NavigationCancel](navigationcancel)` * `[NavigationError](navigationerror)` | | `restoredState?: { [k: string]: any; navigationId: number; } | null` | The navigation state that was previously supplied to the `pushState` call, when the navigation is triggered by a `popstate` event. Otherwise null. The state object is defined by `[NavigationExtras](navigationextras)`, and contains any developer-defined state value, as well as a unique ID that the router assigns to every router transition/navigation. From the perspective of the router, the router never "goes back". When the user clicks on the back button in the browser, a new navigation ID is created. Use the ID in this previous-state object to differentiate between a newly created state and one returned to by a `popstate` event, so that you can restore some remembered state, such as scroll position. | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | angular CanLoadFn CanLoadFn ========= `type-alias` `deprecated` The signature of a function used as a `canLoad` guard on a `[Route](route)`. **Deprecated:** Use `[Route.canMatch](route#canMatch)` and `[CanMatchFn](canmatchfn)` instead ``` type CanLoadFn = (route: Route, segments: UrlSegment[]) => Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree; ``` See also -------- * `[CanLoad](canload)` * `[Route](route)` * `[CanMatchFn](canmatchfn)` angular withPreloading withPreloading ============== `function` Allows to configure a preloading strategy to use. The strategy is configured by providing a reference to a class that implements a `[PreloadingStrategy](preloadingstrategy)`. ### `withPreloading(preloadingStrategy: Type<PreloadingStrategy>): PreloadingFeature` ###### Parameters | | | | | --- | --- | --- | | `preloadingStrategy` | `[Type](../core/type)<[PreloadingStrategy](preloadingstrategy)>` | A reference to a class that implements a `[PreloadingStrategy](preloadingstrategy)` that should be used. | ###### Returns `[PreloadingFeature](preloadingfeature)`: A set of providers for use with `[provideRouter](providerouter)`. See also -------- * `[provideRouter](providerouter)` Usage notes ----------- Basic example of how you can configure preloading: ``` const appRoutes: Routes = []; bootstrapApplication(AppComponent, { providers: [ provideRouter(appRoutes, withPreloading(PreloadAllModules)) ] } ); ``` angular withDebugTracing withDebugTracing ================ `function` Enables logging of all internal navigation events to the console. Extra logging might be useful for debugging purposes to inspect Router event sequence. ### `withDebugTracing(): DebugTracingFeature` ###### Parameters There are no parameters. ###### Returns `[DebugTracingFeature](debugtracingfeature)`: A set of providers for use with `[provideRouter](providerouter)`. See also -------- * `[provideRouter](providerouter)` Usage notes ----------- Basic example of how you can enable debug tracing: ``` const appRoutes: Routes = []; bootstrapApplication(AppComponent, { providers: [ provideRouter(appRoutes, withDebugTracing()) ] } ); ``` angular UrlSegment UrlSegment ========== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Represents a single URL segment. [See more...](urlsegment#description) ``` class UrlSegment { constructor(path: string, parameters: { [name: string]: string; }) path: string parameters: {...} parameterMap: ParamMap toString(): string } ``` Description ----------- A UrlSegment is a part of a URL between the two slashes. It contains a path and the matrix parameters associated with the segment. Further information is available in the [Usage Notes...](urlsegment#usage-notes) Constructor ----------- | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | | `constructor(path: string, parameters: { [name: string]: string; })` Parameters | | | | | --- | --- | --- | | `path` | `string` | The path part of a URL segment | | `parameters` | `object` | The matrix parameters associated with a segment | | Properties ---------- | Property | Description | | --- | --- | | `path: string` | Declared in Constructor The path part of a URL segment | | `parameters: { [name: string]: string; }` | Declared in Constructor The matrix parameters associated with a segment | | `parameterMap: [ParamMap](parammap)` | Read-Only | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | Usage notes ----------- ### Example ``` @Component({templateUrl:'template.html'}) class MyComponent { constructor(router: Router) { const tree: UrlTree = router.parseUrl('/team;id=33'); const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET]; const s: UrlSegment[] = g.segments; s[0].path; // returns 'team' s[0].parameters; // returns {id: 33} } } ```
programming_docs
angular PreloadAllModules PreloadAllModules ================= `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Provides a preloading strategy that preloads all modules as quickly as possible. [See more...](preloadallmodules#description) ``` class PreloadAllModules implements PreloadingStrategy { preload(route: Route, fn: () => Observable<any>): Observable<any> } ``` Provided in ----------- * ``` 'root' ``` Description ----------- ``` RouterModule.forRoot(ROUTES, {preloadingStrategy: PreloadAllModules}) ``` Methods ------- | preload() | | --- | | `preload(route: Route, fn: () => Observable<any>): Observable<any>` Parameters | | | | | --- | --- | --- | | `route` | `[Route](route)` | | | `fn` | `() => Observable<any>` | | Returns `Observable<any>` | angular CanActivate CanActivate =========== `interface` Interface that a class can implement to be a guard deciding if a route can be activated. If all guards return `true`, navigation continues. If any guard returns `false`, navigation is cancelled. If any guard returns a `[UrlTree](urltree)`, the current navigation is cancelled and a new navigation begins to the `[UrlTree](urltree)` returned from the guard. [See more...](canactivate#description) ``` interface CanActivate { canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree } ``` Description ----------- The following example implements a `[CanActivate](canactivate)` function that checks whether the current user has permission to activate the requested route. ``` class UserToken {} class Permissions { canActivate(): boolean { return true; } } @Injectable() class CanActivateTeam implements CanActivate { constructor(private permissions: Permissions, private currentUser: UserToken) {} canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree { return this.permissions.canActivate(this.currentUser, route.params.id); } } ``` Here, the defined guard function is provided as part of the `[Route](route)` object in the router configuration: ``` @NgModule({ imports: [ RouterModule.forRoot([ { path: 'team/:id', component: TeamComponent, canActivate: [CanActivateTeam] } ]) ], providers: [CanActivateTeam, UserToken, Permissions] }) class AppModule {} ``` You can alternatively provide an in-line function with the `[CanActivateFn](canactivatefn)` signature: ``` @NgModule({ imports: [ RouterModule.forRoot([ { path: 'team/:id', component: TeamComponent, canActivate: [(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => true] } ]) ], }) class AppModule {} ``` Methods ------- | canActivate() | | --- | | `canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree` Parameters | | | | | --- | --- | --- | | `route` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | | `state` | `[RouterStateSnapshot](routerstatesnapshot)` | | Returns `Observable<boolean | [UrlTree](urltree)> | Promise<boolean | [UrlTree](urltree)> | boolean | [UrlTree](urltree)` | angular QueryParamsHandling QueryParamsHandling =================== `type-alias` How to handle query parameters in a router link. One of: * `"merge"` : Merge new parameters with current parameters. * `"preserve"` : Preserve current parameters. * `""` : Replace current parameters with new parameters. This is the default behavior. ``` type QueryParamsHandling = 'merge' | 'preserve' | ''; ``` See also -------- * `[UrlCreationOptions](urlcreationoptions)#queryParamsHandling` * `[RouterLink](routerlink)` angular Scroll Scroll ====== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An event triggered by scrolling. ``` class Scroll { constructor(routerEvent: NavigationEnd, position: [number, number], anchor: string) type: EventType.Scroll routerEvent: NavigationEnd position: [...] anchor: string | null toString(): string } ``` Constructor ----------- | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `constructor(routerEvent: NavigationEnd, position: [number, number], anchor: string)` Parameters | | | | | --- | --- | --- | | `routerEvent` | `[NavigationEnd](navigationend)` | | | `position` | `[number, number]` | | | `anchor` | `string` | | | Properties ---------- | Property | Description | | --- | --- | | `type: [EventType.Scroll](eventtype#Scroll)` | Read-Only | | `routerEvent: [NavigationEnd](navigationend)` | Read-Only Declared in Constructor | | `position: [ number, number ] | null` | Read-Only Declared in Constructor | | `anchor: string | null` | Read-Only Declared in Constructor | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | angular @angular/router/testing @angular/router/testing ======================= `entry-point` Supplies a testing module for the Angular `[Router](router)` subsystem. Entry point exports ------------------- ### NgModules | | | | --- | --- | | `[RouterTestingModule](testing/routertestingmodule)` | Sets up the router to be used for testing. | ### Functions | | | | --- | --- | | `[setupTestingRouter](testing/setuptestingrouter)` | **Deprecated:** Use `[provideRouter](providerouter)` or `[RouterTestingModule](testing/routertestingmodule)` instead. Router setup factory function used for testing. | angular DefaultUrlSerializer DefaultUrlSerializer ==================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` A default implementation of the `[UrlSerializer](urlserializer)`. [See more...](defaulturlserializer#description) ``` class DefaultUrlSerializer implements UrlSerializer { parse(url: string): UrlTree serialize(tree: UrlTree): string } ``` Description ----------- Example URLs: ``` /inbox/33(popup:compose) /inbox/33;open=true/messages/44 ``` DefaultUrlSerializer uses parentheses to serialize secondary segments (e.g., popup:compose), the colon syntax to specify the outlet, and the ';parameter=value' syntax (e.g., open=true) to specify route specific parameters. Methods ------- | parse() | | --- | | Parses a url into a `[UrlTree](urltree)` | | `parse(url: string): UrlTree` Parameters | | | | | --- | --- | --- | | `url` | `string` | | Returns `[UrlTree](urltree)` | | serialize() | | --- | | Converts a `[UrlTree](urltree)` into a url | | `serialize(tree: UrlTree): string` Parameters | | | | | --- | --- | --- | | `tree` | `[UrlTree](urltree)` | | Returns `string` | angular UrlMatcher UrlMatcher ========== `type-alias` A function for matching a route against URLs. Implement a custom URL matcher for `[Route.matcher](route#matcher)` when a combination of `path` and `pathMatch` is not expressive enough. Cannot be used together with `path` and `pathMatch`. [See more...](urlmatcher#description) ``` type UrlMatcher = (segments: UrlSegment[], group: UrlSegmentGroup, route: Route) => UrlMatchResult | null; ``` Description ----------- The function takes the following arguments and returns a `[UrlMatchResult](urlmatchresult)` object. * *segments* : An array of URL segments. * *group* : A segment group. * *route* : The route to match against. The following example implementation matches HTML files. ``` export function htmlFiles(url: UrlSegment[]) { return url.length === 1 && url[0].path.endsWith('.html') ? ({consumed: url}) : null; } export const routes = [{ matcher: htmlFiles, component: AnyComponent }]; ``` angular RouterOutlet RouterOutlet ============ `directive` Acts as a placeholder that Angular dynamically fills based on the current router state. [See more...](routeroutlet#description) See also -------- * [Routing tutorial](../../guide/router-tutorial-toh#named-outlets "Example of a named outlet and secondary route configuration"). * `[RouterLink](routerlink)` * `[Route](route)` Exported from ------------- * [``` RouterModule ```](routermodule) Selectors --------- * `[router-outlet](routeroutlet)` Properties ---------- | Property | Description | | --- | --- | | `@[Input](../core/input)()name: [PRIMARY\_OUTLET](primary_outlet)` | The name of the outlet See also:* [named outlets](../../guide/router-tutorial-toh#displaying-multiple-routes-in-named-outlets) | | `@[Output](../core/output)('activate')activateEvents: [EventEmitter](../core/eventemitter)<any>` | | | `@[Output](../core/output)('deactivate')deactivateEvents: [EventEmitter](../core/eventemitter)<any>` | | | `@[Output](../core/output)('attach')attachEvents: [EventEmitter](../core/eventemitter)<unknown>` | Emits an attached component instance when the `[RouteReuseStrategy](routereusestrategy)` instructs to re-attach a previously detached subtree. | | `@[Output](../core/output)('detach')detachEvents: [EventEmitter](../core/eventemitter)<unknown>` | Emits a detached component instance when the `[RouteReuseStrategy](routereusestrategy)` instructs to detach the subtree. | | `isActivated: boolean` | Read-Only | | `component: Object` | Read-Only | | `activatedRoute: [ActivatedRoute](activatedroute)` | Read-Only | | `activatedRouteData: [Data](data)` | Read-Only | Template variable references ---------------------------- | Identifier | Usage | | --- | --- | | `outlet` | `#myTemplateVar="outlet"` | Description ----------- Each outlet can have a unique name, determined by the optional `name` attribute. The name cannot be set or changed dynamically. If not set, default value is "primary". ``` <router-outlet></router-outlet> <router-outlet name='left'></router-outlet> <router-outlet name='right'></router-outlet> ``` Named outlets can be the targets of secondary routes. The `[Route](route)` object for a secondary route has an `outlet` property to identify the target outlet: `{path: <base-path>, component: <component>, outlet: <target_outlet_name>}` Using named outlets and secondary routes, you can target multiple outlets in the same `[RouterLink](routerlink)` directive. The router keeps track of separate branches in a navigation tree for each named outlet and generates a representation of that tree in the URL. The URL for a secondary route uses the following syntax to specify both the primary and secondary routes at the same time: `http://base-path/primary-route-path(outlet-name:route-path)` A router outlet emits an activate event when a new component is instantiated, deactivate event when a component is destroyed. An attached event emits when the `[RouteReuseStrategy](routereusestrategy)` instructs the outlet to reattach the subtree, and the detached event emits when the `[RouteReuseStrategy](routereusestrategy)` instructs the outlet to detach the subtree. ``` <router-outlet (activate)='onActivate($event)' (deactivate)='onDeactivate($event)' (attach)='onAttach($event)' (detach)='onDetach($event)'></router-outlet> ``` Methods ------- | detach() | | --- | | Called when the `[RouteReuseStrategy](routereusestrategy)` instructs to detach the subtree | | `detach(): ComponentRef<any>` Parameters There are no parameters. Returns `[ComponentRef](../core/componentref)<any>` | | attach() | | --- | | Called when the `[RouteReuseStrategy](routereusestrategy)` instructs to re-attach a previously detached subtree | | `attach(ref: ComponentRef<any>, activatedRoute: ActivatedRoute)` Parameters | | | | | --- | --- | --- | | `ref` | `[ComponentRef](../core/componentref)<any>` | | | `activatedRoute` | `[ActivatedRoute](activatedroute)` | | | | deactivate() | | --- | | `deactivate(): void` Parameters There are no parameters. Returns `void` | | activateWith() | | --- | | `activateWith(activatedRoute: ActivatedRoute, resolverOrInjector?: EnvironmentInjector | ComponentFactoryResolver)` Parameters | | | | | --- | --- | --- | | `activatedRoute` | `[ActivatedRoute](activatedroute)` | | | `resolverOrInjector` | `[EnvironmentInjector](../core/environmentinjector) | [ComponentFactoryResolver](../core/componentfactoryresolver)` | Optional. Default is `undefined`. | | angular BaseRouteReuseStrategy BaseRouteReuseStrategy ====================== `class` This base route reuse strategy only reuses routes when the matched router configs are identical. This prevents components from being destroyed and recreated when just the route parameters, query parameters or fragment change (that is, the existing component is *reused*). [See more...](baseroutereusestrategy#description) ``` abstract class BaseRouteReuseStrategy implements RouteReuseStrategy { shouldDetach(route: ActivatedRouteSnapshot): boolean store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void shouldAttach(route: ActivatedRouteSnapshot): boolean retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean } ``` Description ----------- This strategy does not store any routes for later reuse. Angular uses this strategy by default. It can be used as a base class for custom route reuse strategies, i.e. you can create your own class that extends the `[BaseRouteReuseStrategy](baseroutereusestrategy)` one. Methods ------- | shouldDetach() | | --- | | Whether the given route should detach for later reuse. Always returns false for `[BaseRouteReuseStrategy](baseroutereusestrategy)`. | | `shouldDetach(route: ActivatedRouteSnapshot): boolean` Parameters | | | | | --- | --- | --- | | `route` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | Returns `boolean` | | store() | | --- | | A no-op; the route is never stored since this strategy never detaches routes for later re-use. | | `store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void` Parameters | | | | | --- | --- | --- | | `route` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | | `detachedTree` | `[DetachedRouteHandle](detachedroutehandle)` | | Returns `void` | | shouldAttach() | | --- | | Returns `false`, meaning the route (and its subtree) is never reattached | | `shouldAttach(route: ActivatedRouteSnapshot): boolean` Parameters | | | | | --- | --- | --- | | `route` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | Returns `boolean` | | retrieve() | | --- | | Returns `null` because this strategy does not store routes for later re-use. | | `retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null` Parameters | | | | | --- | --- | --- | | `route` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | Returns `[DetachedRouteHandle](detachedroutehandle) | null` | | shouldReuseRoute() | | --- | | Determines if a route should be reused. This strategy returns `true` when the future route config and current route config are identical. | | `shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean` Parameters | | | | | --- | --- | --- | | `future` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | | `curr` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | Returns `boolean` | angular RouterModule RouterModule ============ `ngmodule` Adds directives and providers for in-app navigation among views defined in an application. Use the Angular `[Router](router)` service to declaratively specify application states and manage state transitions. [See more...](routermodule#description) ``` class RouterModule { static forRoot(routes: Routes, config?: ExtraOptions): ModuleWithProviders<RouterModule> static forChild(routes: Routes): ModuleWithProviders<RouterModule> } ``` See also -------- * [Routing and Navigation guide](../../guide/router) for an overview of how the `[Router](router)` service should be used. Description ----------- You can import this NgModule multiple times, once for each lazy-loaded bundle. However, only one `[Router](router)` service can be active. To ensure this, there are two ways to register routes when importing this module: * The `forRoot()` method creates an `[NgModule](../core/ngmodule)` that contains all the directives, the given routes, and the `[Router](router)` service itself. * The `forChild()` method creates an `[NgModule](../core/ngmodule)` that contains all the directives and the given routes, but does not include the `[Router](router)` service. Static methods -------------- | forRoot() | | --- | | Creates and configures a module with all the router providers and directives. Optionally sets up an application listener to perform an initial navigation. | | `static forRoot(routes: Routes, config?: ExtraOptions): ModuleWithProviders<RouterModule>` Parameters | | | | | --- | --- | --- | | `routes` | `[Routes](routes)` | An array of `[Route](route)` objects that define the navigation paths for the application. | | `config` | `[ExtraOptions](extraoptions)` | An `[ExtraOptions](extraoptions)` configuration object that controls how navigation is performed. Optional. Default is `undefined`. | Returns `[ModuleWithProviders](../core/modulewithproviders)<[RouterModule](routermodule)>`: The new `[NgModule](../core/ngmodule)`. | | When registering the NgModule at the root, import as follows: ``` @NgModule({ imports: [RouterModule.forRoot(ROUTES)] }) class MyNgModule {} ``` | | forChild() | | --- | | Creates a module with all the router directives and a provider registering routes, without creating a new Router service. When registering for submodules and lazy-loaded submodules, create the NgModule as follows: | | `static forChild(routes: Routes): ModuleWithProviders<RouterModule>` Parameters | | | | | --- | --- | --- | | `routes` | `[Routes](routes)` | An array of `[Route](route)` objects that define the navigation paths for the submodule. | Returns `[ModuleWithProviders](../core/modulewithproviders)<[RouterModule](routermodule)>`: The new NgModule. | | ``` @NgModule({ imports: [RouterModule.forChild(ROUTES)] }) class MyNgModule {} ``` | Directives ---------- | Name | Description | | --- | --- | | [``` RouterLink ```](routerlink) | When applied to an element in a template, makes that element a link that initiates navigation to a route. Navigation opens one or more routed components in one or more `<[router-outlet](routeroutlet)>` locations on the page. | | [``` RouterLinkActive ```](routerlinkactive) | Tracks whether the linked route of an element is currently active, and allows you to specify one or more CSS classes to add to the element when the linked route is active. | | [``` RouterLinkWithHref ```](routerlinkwithhref) | When applied to an element in a template, makes that element a link that initiates navigation to a route. Navigation opens one or more routed components in one or more `<[router-outlet](routeroutlet)>` locations on the page. | | [``` RouterOutlet ```](routeroutlet) | Acts as a placeholder that Angular dynamically fills based on the current router state. | angular NavigationBehaviorOptions NavigationBehaviorOptions ========================= `interface` Options that modify the `[Router](router)` navigation strategy. Supply an object containing any of these properties to a `[Router](router)` navigation function to control how the navigation should be handled. ``` interface NavigationBehaviorOptions { onSameUrlNavigation?: Extract<OnSameUrlNavigation, 'reload'> skipLocationChange?: boolean replaceUrl?: boolean state?: {...} } ``` Child interfaces ---------------- * `[NavigationExtras](navigationextras)` See also -------- * [Router.navigate() method](router#navigate) * [Router.navigateByUrl() method](router#navigatebyurl) * [Routing and Navigation guide](../../guide/router) Properties ---------- | Property | Description | | --- | --- | | `onSameUrlNavigation?: Extract<[OnSameUrlNavigation](onsameurlnavigation), 'reload'>` | How to handle a navigation request to the current URL. This value is a subset of the options available in `[OnSameUrlNavigation](onsameurlnavigation)` and will take precedence over the default value set for the `[Router](router)`. See also:* `[OnSameUrlNavigation](onsameurlnavigation)` * `[RouterConfigOptions](routerconfigoptions)` | | `skipLocationChange?: boolean` | When true, navigates without pushing a new state into history. ``` // Navigate silently to /view this.router.navigate(['/view'], { skipLocationChange: true }); ``` | | `replaceUrl?: boolean` | When true, navigates while replacing the current state in history. ``` // Navigate to /view this.router.navigate(['/view'], { replaceUrl: true }); ``` | | `state?: { [k: string]: any; }` | Developer-defined state that can be passed to any navigation. Access this value through the `[Navigation.extras](navigation#extras)` object returned from the [Router.getCurrentNavigation() method](router#getcurrentnavigation) while a navigation is executing. After a navigation completes, the router writes an object containing this value together with a `navigationId` to `history.state`. The value is written when `location.go()` or `location.replaceState()` is called before activating this route. Note that `history.state` does not pass an object equality test because the router adds the `navigationId` on each navigation. |
programming_docs
angular InitialNavigation InitialNavigation ================= `type-alias` Allowed values in an `[ExtraOptions](extraoptions)` object that configure when the router performs the initial navigation operation. [See more...](initialnavigation#description) ``` type InitialNavigation = 'disabled' | 'enabledBlocking' | 'enabledNonBlocking'; ``` See also -------- * `forRoot()` Description ----------- * 'enabledNonBlocking' - (default) The initial navigation starts after the root component has been created. The bootstrap is not blocked on the completion of the initial navigation. * 'enabledBlocking' - The initial navigation starts before the root component is created. The bootstrap is blocked until the initial navigation is complete. This value is required for [server-side rendering](../../guide/universal) to work. * 'disabled' - The initial navigation is not performed. The location listener is set up before the root component gets created. Use if there is a reason to have more control over when the router starts its initial navigation due to some complex initialization logic. angular RouterState RouterState =========== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Represents the state of the router as a tree of activated routes. ``` class RouterState extends Tree<ActivatedRoute> { snapshot: RouterStateSnapshot toString(): string } ``` See also -------- * `[ActivatedRoute](activatedroute)` * [Getting route information](../../guide/router#getting-route-information) Constructor ----------- | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | | `constructor(root: TreeNode<ActivatedRoute>, snapshot: RouterStateSnapshot)` Parameters | | | | | --- | --- | --- | | `root` | `TreeNode<[ActivatedRoute](activatedroute)>` | | | `snapshot` | `[RouterStateSnapshot](routerstatesnapshot)` | The current snapshot of the router state | | Properties ---------- | Property | Description | | --- | --- | | `snapshot: [RouterStateSnapshot](routerstatesnapshot)` | Declared in Constructor The current snapshot of the router state | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | Usage notes ----------- Every node in the route tree is an `[ActivatedRoute](activatedroute)` instance that knows about the "consumed" URL segments, the extracted parameters, and the resolved data. Use the `[ActivatedRoute](activatedroute)` properties to traverse the tree from any node. The following fragment shows how a component gets the root node of the current state to establish its own route tree: ``` @Component({templateUrl:'template.html'}) class MyComponent { constructor(router: Router) { const state: RouterState = router.routerState; const root: ActivatedRoute = state.root; const child = root.firstChild; const id: Observable<string> = child.params.map(p => p.id); //... } } ``` angular ResolveEnd ResolveEnd ========== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An event triggered at the end of the Resolve phase of routing. ``` class ResolveEnd extends RouterEvent { constructor(id: number, url: string, urlAfterRedirects: string, state: RouterStateSnapshot) type: EventType.ResolveEnd urlAfterRedirects: string state: RouterStateSnapshot toString(): string // inherited from router/RouterEvent constructor(id: number, url: string) id: number url: string } ``` See also -------- * `[ResolveStart](resolvestart)`. Constructor ----------- | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `constructor(id: number, url: string, urlAfterRedirects: string, state: RouterStateSnapshot)` Parameters | | | | | --- | --- | --- | | `id` | `number` | | | `url` | `string` | | | `urlAfterRedirects` | `string` | | | `state` | `[RouterStateSnapshot](routerstatesnapshot)` | | | Properties ---------- | Property | Description | | --- | --- | | `type: [EventType.ResolveEnd](eventtype#ResolveEnd)` | Read-Only | | `urlAfterRedirects: string` | Declared in Constructor | | `state: [RouterStateSnapshot](routerstatesnapshot)` | Declared in Constructor | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | angular UrlHandlingStrategy UrlHandlingStrategy =================== `class` Provides a way to migrate AngularJS applications to Angular. ``` abstract class UrlHandlingStrategy { abstract shouldProcessUrl(url: UrlTree): boolean abstract extract(url: UrlTree): UrlTree abstract merge(newUrlPart: UrlTree, rawUrl: UrlTree): UrlTree } ``` Provided in ----------- * ``` 'root' ``` Methods ------- | shouldProcessUrl() | | --- | | Tells the router if this URL should be processed. | | `abstract shouldProcessUrl(url: UrlTree): boolean` Parameters | | | | | --- | --- | --- | | `url` | `[UrlTree](urltree)` | | Returns `boolean` | | When it returns true, the router will execute the regular navigation. When it returns false, the router will set the router state to an empty state. As a result, all the active components will be destroyed. | | extract() | | --- | | Extracts the part of the URL that should be handled by the router. The rest of the URL will remain untouched. | | `abstract extract(url: UrlTree): UrlTree` Parameters | | | | | --- | --- | --- | | `url` | `[UrlTree](urltree)` | | Returns `[UrlTree](urltree)` | | merge() | | --- | | Merges the URL fragment with the rest of the URL. | | `abstract merge(newUrlPart: UrlTree, rawUrl: UrlTree): UrlTree` Parameters | | | | | --- | --- | --- | | `newUrlPart` | `[UrlTree](urltree)` | | | `rawUrl` | `[UrlTree](urltree)` | | Returns `[UrlTree](urltree)` | angular LoadChildren LoadChildren ============ `type-alias` A function that returns a set of routes to load. ``` type LoadChildren = LoadChildrenCallback; ``` See also -------- * `[LoadChildrenCallback](loadchildrencallback)` angular ResolveData ResolveData =========== `type-alias` Represents the resolved data associated with a particular route. ``` type ResolveData = { [key: string | symbol]: any | ResolveFn<unknown>; }; ``` See also -------- * `[Route](route)#resolve`. angular ChildrenOutletContexts ChildrenOutletContexts ====================== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` Store contextual information about the children (= nested) `[RouterOutlet](routeroutlet)` ``` class ChildrenOutletContexts { onChildOutletCreated(childName: string, outlet: RouterOutletContract): void onChildOutletDestroyed(childName: string): void onOutletDeactivated(): Map<string, OutletContext> onOutletReAttached(contexts: Map<string, OutletContext>) getOrCreateContext(childName: string): OutletContext getContext(childName: string): OutletContext | null } ``` Provided in ----------- * ``` 'root' ``` Methods ------- | onChildOutletCreated() | | --- | | Called when a `[RouterOutlet](routeroutlet)` directive is instantiated | | `onChildOutletCreated(childName: string, outlet: RouterOutletContract): void` Parameters | | | | | --- | --- | --- | | `childName` | `string` | | | `outlet` | `[RouterOutletContract](routeroutletcontract)` | | Returns `void` | | onChildOutletDestroyed() | | --- | | Called when a `[RouterOutlet](routeroutlet)` directive is destroyed. We need to keep the context as the outlet could be destroyed inside a NgIf and might be re-created later. | | `onChildOutletDestroyed(childName: string): void` Parameters | | | | | --- | --- | --- | | `childName` | `string` | | Returns `void` | | onOutletDeactivated() | | --- | | Called when the corresponding route is deactivated during navigation. Because the component get destroyed, all children outlet are destroyed. | | `onOutletDeactivated(): Map<string, OutletContext>` Parameters There are no parameters. Returns `Map<string, [OutletContext](outletcontext)>` | | onOutletReAttached() | | --- | | `onOutletReAttached(contexts: Map<string, OutletContext>)` Parameters | | | | | --- | --- | --- | | `contexts` | `Map<string, [OutletContext](outletcontext)>` | | | | getOrCreateContext() | | --- | | `getOrCreateContext(childName: string): OutletContext` Parameters | | | | | --- | --- | --- | | `childName` | `string` | | Returns `[OutletContext](outletcontext)` | | getContext() | | --- | | `getContext(childName: string): OutletContext | null` Parameters | | | | | --- | --- | --- | | `childName` | `string` | | Returns `[OutletContext](outletcontext) | null` | angular Navigation Navigation ========== `interface` Information about a navigation operation. Retrieve the most recent navigation object with the [Router.getCurrentNavigation() method](router#getcurrentnavigation) . [See more...](navigation#description) ``` interface Navigation { id: number initialUrl: UrlTree extractedUrl: UrlTree finalUrl?: UrlTree trigger: 'imperative' | 'popstate' | 'hashchange' extras: NavigationExtras previousNavigation: Navigation | null } ``` Description ----------- * *id* : The unique identifier of the current navigation. * *initialUrl* : The target URL passed into the `[Router](router)#navigateByUrl()` call before navigation. This is the value before the router has parsed or applied redirects to it. * *extractedUrl* : The initial target URL after being parsed with `UrlSerializer.extract()`. * *finalUrl* : The extracted URL after redirects have been applied. This URL may not be available immediately, therefore this property can be `undefined`. It is guaranteed to be set after the `[RoutesRecognized](routesrecognized)` event fires. * *trigger* : Identifies how this navigation was triggered. -- 'imperative'--Triggered by `router.navigateByUrl` or `router.navigate`. -- 'popstate'--Triggered by a popstate event. -- 'hashchange'--Triggered by a hashchange event. * *extras* : A `[NavigationExtras](navigationextras)` options object that controlled the strategy used for this navigation. * *previousNavigation* : The previously successful `[Navigation](navigation)` object. Only one previous navigation is available, therefore this previous `[Navigation](navigation)` object has a `null` value for its own `previousNavigation`. Properties ---------- | Property | Description | | --- | --- | | `id: number` | The unique identifier of the current navigation. | | `initialUrl: [UrlTree](urltree)` | The target URL passed into the `[Router](router)#navigateByUrl()` call before navigation. This is the value before the router has parsed or applied redirects to it. | | `extractedUrl: [UrlTree](urltree)` | The initial target URL after being parsed with `UrlHandlingStrategy.extract()`. | | `finalUrl?: [UrlTree](urltree)` | The extracted URL after redirects have been applied. This URL may not be available immediately, therefore this property can be `undefined`. It is guaranteed to be set after the `[RoutesRecognized](routesrecognized)` event fires. | | `[trigger](../animations/trigger): 'imperative' | 'popstate' | 'hashchange'` | Identifies how this navigation was triggered.* 'imperative'--Triggered by `router.navigateByUrl` or `router.navigate`. * 'popstate'--Triggered by a popstate event. * 'hashchange'--Triggered by a hashchange event. | | `extras: [NavigationExtras](navigationextras)` | Options that controlled the strategy used for this navigation. See `[NavigationExtras](navigationextras)`. | | `previousNavigation: [Navigation](navigation) | null` | The previously successful `[Navigation](navigation)` object. Only one previous navigation is available, therefore this previous `[Navigation](navigation)` object has a `null` value for its own `previousNavigation`. | angular Resolve Resolve ======= `interface` Interface that classes can implement to be a data provider. A data provider class can be used with the router to resolve data during navigation. The interface defines a `resolve()` method that is invoked right after the `[ResolveStart](resolvestart)` router event. The router waits for the data to be resolved before the route is finally activated. [See more...](resolve#description) ``` interface Resolve<T> { resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<T> | Promise<T> | T } ``` Description ----------- The following example implements a `resolve()` method that retrieves the data needed to activate the requested route. ``` @Injectable({ providedIn: 'root' }) export class HeroResolver implements Resolve<Hero> { constructor(private service: HeroService) {} resolve( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<Hero>|Promise<Hero>|Hero { return this.service.getHero(route.paramMap.get('id')); } } ``` Here, the defined `resolve()` function is provided as part of the `[Route](route)` object in the router configuration: ``` @NgModule({ imports: [ RouterModule.forRoot([ { path: 'detail/:id', component: HeroDetailComponent, resolve: { hero: HeroResolver } } ]) ], exports: [RouterModule] }) export class AppRoutingModule {} ``` You can alternatively provide an in-line function with the `[ResolveFn](resolvefn)` signature: ``` export const myHero: Hero = { // ... } @NgModule({ imports: [ RouterModule.forRoot([ { path: 'detail/:id', component: HeroComponent, resolve: { hero: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => myHero } } ]) ], }) export class AppModule {} ``` And you can access to your resolved data from `HeroComponent`: ``` @Component({ selector: "app-hero", templateUrl: "hero.component.html", }) export class HeroComponent { constructor(private activatedRoute: ActivatedRoute) {} ngOnInit() { this.activatedRoute.data.subscribe(({ hero }) => { // do something with your resolved data ... }) } } ``` Further information is available in the [Usage Notes...](resolve#usage-notes) Methods ------- | resolve() | | --- | | `resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<T> | Promise<T> | T` Parameters | | | | | --- | --- | --- | | `route` | `[ActivatedRouteSnapshot](activatedroutesnapshot)` | | | `state` | `[RouterStateSnapshot](routerstatesnapshot)` | | Returns `Observable<T> | Promise<T> | T` | Usage notes ----------- When both guard and resolvers are specified, the resolvers are not executed until all guards have run and succeeded. For example, consider the following route configuration: ``` { path: 'base' canActivate: [BaseGuard], resolve: {data: BaseDataResolver} children: [ { path: 'child', guards: [ChildGuard], component: ChildComponent, resolve: {childData: ChildDataResolver} } ] } ``` The order of execution is: BaseGuard, ChildGuard, BaseDataResolver, ChildDataResolver. angular GuardsCheckEnd GuardsCheckEnd ============== `class` `[final](https://github.com/angular/angular/tree/15.1.5/docs/PUBLIC_API.md#final-classes)` An event triggered at the end of the Guard phase of routing. ``` class GuardsCheckEnd extends RouterEvent { constructor(id: number, url: string, urlAfterRedirects: string, state: RouterStateSnapshot, shouldActivate: boolean) type: EventType.GuardsCheckEnd urlAfterRedirects: string state: RouterStateSnapshot shouldActivate: boolean toString(): string // inherited from router/RouterEvent constructor(id: number, url: string) id: number url: string } ``` See also -------- * `[GuardsCheckStart](guardscheckstart)` Constructor ----------- | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | `constructor(id: number, url: string, urlAfterRedirects: string, state: RouterStateSnapshot, shouldActivate: boolean)` Parameters | | | | | --- | --- | --- | | `id` | `number` | | | `url` | `string` | | | `urlAfterRedirects` | `string` | | | `state` | `[RouterStateSnapshot](routerstatesnapshot)` | | | `shouldActivate` | `boolean` | | | Properties ---------- | Property | Description | | --- | --- | | `type: [EventType.GuardsCheckEnd](eventtype#GuardsCheckEnd)` | Read-Only | | `urlAfterRedirects: string` | Declared in Constructor | | `state: [RouterStateSnapshot](routerstatesnapshot)` | Declared in Constructor | | `shouldActivate: boolean` | Declared in Constructor | Methods ------- | toString() | | --- | | `toString(): string` Parameters There are no parameters. Returns `string` | angular setUpLocationSync setUpLocationSync ================= `function` Sets up a location change listener to trigger `history.pushState`. Works around the problem that `onPopState` does not trigger `history.pushState`. Must be called *after* calling `UpgradeModule.bootstrap`. ### `setUpLocationSync(ngUpgrade: UpgradeModule, urlType: "path" | "hash" = 'path')` ###### Parameters | | | | | --- | --- | --- | | `ngUpgrade` | `[UpgradeModule](../../upgrade/static/upgrademodule)` | The upgrade NgModule. | | `urlType` | `"path" | "hash"` | The location strategy. Optional. Default is `'path'`. | See also -------- * `[HashLocationStrategy](../../common/hashlocationstrategy)` * `[PathLocationStrategy](../../common/pathlocationstrategy)` angular RouterUpgradeInitializer RouterUpgradeInitializer ======================== `const` Creates an initializer that sets up `ngRoute` integration along with setting up the Angular router. ### `const RouterUpgradeInitializer: { provide: InjectionToken<((compRef: ComponentRef<any>) => void)[]>; multi: boolean; useFactory: (ngUpgrade: UpgradeModule) => () => void; deps: (typeof UpgradeModule)[]; };` #### Usage notes ``` @NgModule({ imports: [ RouterModule.forRoot(SOME_ROUTES), UpgradeModule ], providers: [ RouterUpgradeInitializer ] }) export class AppModule { ngDoBootstrap() {} } ``` angular setupTestingRouter setupTestingRouter ================== `function` `deprecated` Router setup factory function used for testing. **Deprecated:** Use `[provideRouter](../providerouter)` or `[RouterTestingModule](routertestingmodule)` instead. ### `setupTestingRouter(urlSerializer: UrlSerializer, contexts: ChildrenOutletContexts, location: Location, compiler: Compiler, injector: Injector, routes: Route[][], opts?: ExtraOptions | UrlHandlingStrategy, urlHandlingStrategy?: UrlHandlingStrategy, routeReuseStrategy?: RouteReuseStrategy, titleStrategy?: TitleStrategy)` **Deprecated** Use `[provideRouter](../providerouter)` or `[RouterTestingModule](routertestingmodule)` instead. ###### Parameters | | | | | --- | --- | --- | | `urlSerializer` | `[UrlSerializer](../urlserializer)` | | | `contexts` | `[ChildrenOutletContexts](../childrenoutletcontexts)` | | | `location` | `[Location](../../common/location)` | | | `compiler` | `[Compiler](../../core/compiler)` | | | `injector` | `[Injector](../../core/injector)` | | | `routes` | `[Route](../route)[][]` | | | `opts` | `[ExtraOptions](../extraoptions) | [UrlHandlingStrategy](../urlhandlingstrategy)` | Optional. Default is `undefined`. | | `urlHandlingStrategy` | `[UrlHandlingStrategy](../urlhandlingstrategy)` | Optional. Default is `undefined`. | | `routeReuseStrategy` | `[RouteReuseStrategy](../routereusestrategy)` | Optional. Default is `undefined`. | | `titleStrategy` | `[TitleStrategy](../titlestrategy)` | Optional. Default is `undefined`. | angular RouterTestingModule RouterTestingModule =================== `ngmodule` Sets up the router to be used for testing. [See more...](routertestingmodule#description) ``` class RouterTestingModule { static withRoutes(routes: Routes, config?: ExtraOptions): ModuleWithProviders<RouterTestingModule> } ``` Description ----------- The modules sets up the router to be used for testing. It provides spy implementations of `[Location](../../common/location)` and `[LocationStrategy](../../common/locationstrategy)`. Further information is available in the [Usage Notes...](routertestingmodule#usage-notes) Static methods -------------- | withRoutes() | | --- | | `static withRoutes(routes: Routes, config?: ExtraOptions): ModuleWithProviders<RouterTestingModule>` Parameters | | | | | --- | --- | --- | | `routes` | `[Routes](../routes)` | | | `config` | `[ExtraOptions](../extraoptions)` | Optional. Default is `undefined`. | Returns `[ModuleWithProviders](../../core/modulewithproviders)<[RouterTestingModule](routertestingmodule)>` | Providers --------- | Provider | | --- | | ``` ROUTER_PROVIDERS ``` | | ``` provideLocationMocks() ``` | | ``` withPreloading(NoPreloading).ɵproviders ``` | | ``` { provide: ROUTES, multi: true, useValue: [] } ``` | Usage notes ----------- ### Example ``` beforeEach(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule.withRoutes( [{path: '', component: BlankCmp}, {path: 'simple', component: SimpleCmp}] ) ] }); }); ```
programming_docs
angular NG8106: Suffix not supported NG8106: Suffix not supported ============================ Description ----------- This diagnostic detects when the `.px`, `.%`, and `.em` suffixes are used with an attribute binding. These suffixes are only available for style bindings. ``` <div [attr.width.px]="5"></div> ``` What should I do instead? ------------------------- Rather than using the `.px`, `.%`, or `.em` suffixes that are only supported in style bindings, move this to the value assignment of the binding. ``` <div [attr.width]="'5px'"></div> ``` What if I can't avoid this? --------------------------- This diagnostic can be disabled by editing the project's `tsconfig.json` file: ``` { "angularCompilerOptions": { "extendedDiagnostics": { "checks": { "suffixNotSupported": "suppress" } } } } ``` See [extended diagnostic configuration](https://angular.io/extended-diagnostics/extended-diagnostics#configuration) for more info. angular NG8101: Invalid Banana-in-Box NG8101: Invalid Banana-in-Box ============================= Description ----------- This diagnostic detects a backwards "banana-in-box" syntax for [two-way bindings](../guide/two-way-binding). ``` <div ([var])="otherVar"></div> ``` What's wrong with that? ----------------------- As it stands, `([var])` is actually an [event binding](../guide/event-binding) with the name `[var]`. The author likely intended this as a two-way binding to a variable named `var` but, as written, this binding has no effect. What should I do instead? ------------------------- Fix the typo. As the name suggests, the banana `(` should go *inside* the box `[]`. In this case: ``` <div [(var)]="otherVar"></div> ``` Configuration requirements -------------------------- [`strictTemplates`](../guide/template-typecheck#strict-mode) must be enabled for any extended diagnostic to emit. `invalidBananaInBox` has no additional requirements beyond `strictTemplates`. What if I can't avoid this? --------------------------- This diagnostic can be disabled by editing the project's `tsconfig.json` file: ``` { "angularCompilerOptions": { "extendedDiagnostics": { "checks": { "invalidBananaInBox": "suppress" } } } } ``` See [extended diagnostic configuration](https://angular.io/extended-diagnostics/extended-diagnostics#configuration) for more info. angular NG8103: Missing control flow directive NG8103: Missing control flow directive ====================================== Description ----------- This diagnostics ensures that a standalone component which uses known control flow directives (such as `*[ngIf](../api/common/ngif)`, `*[ngFor](../api/common/ngfor)`, `*[ngSwitch](../api/common/ngswitch)`) in a template, also imports those directives either individually or by importing the `[CommonModule](../api/common/commonmodule)`. ``` import {Component} from '@angular/core'; @Component({ standalone: true, // Template uses `*ngIf`, but no corresponding directive imported. template: `<div *ngIf="visible">Hi</div>`, // … }) class MyComponent {} ``` How to fix the problem ---------------------- Make sure that a corresponding control flow directive is imported. A directive can be imported individually: ``` import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ standalone: true, imports: [NgIf], template: `<div *ngIf="visible">Hi</div>`, // … }) class MyComponent {} ``` or you could import the entire `[CommonModule](../api/common/commonmodule)`, which contains all control flow directives: ``` import {Component} from '@angular/core'; import {CommonModule} from '@angular/common'; @Component({ standalone: true, imports: [CommonModule], template: `<div *ngIf="visible">Hi</div>`, // … }) class MyComponent {} ``` angular NG8102: Nullish coalescing not nullable NG8102: Nullish coalescing not nullable ======================================= Description ----------- This diagnostic detects a useless nullish coalescing operator (`??`) characters in Angular templates. Specifically, it looks for operations where the input is not "nullable", meaning its type does not include `null` or `undefined`. For such values, the right side of the `??` will never be used. ``` import {Component} from '@angular/core'; @Component({ // Template displays `foo` if present, falls back to 'bar' if it is `null` // or `undefined`. template: `{{ foo ?? 'bar' }}`, // … }) class MyComponent { // `foo` is declared as a `string` which *cannot* be `null` or `undefined`. foo: string = 'test'; } ``` What's wrong with that? ----------------------- Using the nullish coalescing operator with a non-nullable input has no effect and is indicative of a discrepancy between the allowed type of a value and how it is presented in the template. A developer might reasonably assume that the right side of the nullish coalescing operator is displayed in some case, but it will never actually be displayed. This can lead to confusion about the expected output of the program. What should I do instead? ------------------------- Update the template and declared type to be in sync. Double-check the type of the input and confirm whether it is actually expected to be nullable. If the input should be nullable, add `null` or `undefined` to its type to indicate this. ``` import {Component} from '@angular/core'; @Component({ template: `{{ foo ?? 'bar' }}`, // … }) class MyComponent { // `foo` is now nullable. If it is ever set to `null`, 'bar' will be displayed. foo: string | null = 'test'; } ``` If the input should *not* be nullable, delete the `??` operator and its right operand, since the value is guaranteed by TypeScript to always be non-nullable. ``` import {Component} from '@angular/core'; @Component({ // Template always displays `foo`, which is guaranteed to never be `null` or // `undefined`. template: `{{ foo }}`, // … }) class MyComponent { foo: string = 'test'; } ``` Configuration requirements -------------------------- [`strictTemplates`](../guide/template-typecheck#strict-mode) must be enabled for any extended diagnostic to emit. [`strictNullChecks`](../guide/template-typecheck#strict-null-checks) must also be enabled to emit any `nullishCoalescingNotNullable` diagnostics. What if I can't avoid this? --------------------------- This diagnostic can be disabled by editing the project's `tsconfig.json` file: ``` { "angularCompilerOptions": { "extendedDiagnostics": { "checks": { "nullishCoalescingNotNullable": "suppress" } } } } ``` See [extended diagnostic configuration](https://angular.io/extended-diagnostics/extended-diagnostics#configuration) for more info. angular NG8105: Missing `let` keyword in an *ngFor expression NG8105: Missing `let` keyword in an \*ngFor expression ====================================================== Description ----------- This diagnostic is emitted when an expression used in `*[ngFor](../api/common/ngfor)` is missing the `let` keyword. ``` import {Component} from '@angular/core'; @Component({ // The `let` keyword is missing in the `*ngFor` expression. template: `<div *ngFor="item of items">{{ item }}</div>`, // … }) class MyComponent { items = [1, 2, 3]; } ``` How to resolve the problem -------------------------- Add the missing `let` keyword. ``` import {Component} from '@angular/core'; @Component({ // The `let` keyword is now present in the `*ngFor` expression, // no diagnostic messages are emitted in this case. template: `<div *ngFor="let item of items">{{ item }}</div>`, // … }) class MyComponent { items = [1, 2, 3]; } ``` angular NG8104: Text attribute not binding NG8104: Text attribute not binding ================================== Description ----------- This diagnostic ensures that attributes which have the "special" Angular binding prefix (`attr.`, `style.`, and `class.`) are interpreted as bindings. For example, `<div attr.id="my-id"></div>` will not interpret this as an attribute binding to `id` but rather just a regular attribute and will appear as-is in the final HTML (`<div attr.id="my-id"></div>`). This is likely not the intent of the developer. Instead, the intent is likely to have the `id` be set to 'my-id' (`<div id="my-id"></div>`). What should I do instead? ------------------------- When binding to `attr.`, `class.`, or `style.`, ensure you use the Angular template binding syntax. ``` <div [attr.id]="my-id"></div> <div [style.color]="red"></div> <div [class.blue]="true"></div> ``` What if I can't avoid this? --------------------------- This diagnostic can be disabled by editing the project's `tsconfig.json` file: ``` { "angularCompilerOptions": { "extendedDiagnostics": { "checks": { "textAttributeNotBinding": "suppress" } } } } ``` See [extended diagnostic configuration](https://angular.io/extended-diagnostics/extended-diagnostics#configuration) for more info. angular NG0203: `inject()` must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `EnvironmentInjector#runInContext`. NG0203: `inject()` must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `EnvironmentInjector#runInContext`. ======================================================================================================================================================================================= Description ----------- You see this error when you try to use the `inject()` function outside of the allowed injection context. The injection context is available during the class creation and initialization. It is also available to functions used with `[EnvironmentInjector](../api/core/environmentinjector)#runInContext`. In practice the `inject()` calls are allowed in a constructor, a constructor parameter and a field initializer: ``` @Injectable({providedIn: 'root'}) export class Car { radio: Radio|undefined; // OK: field initializer spareTyre = inject(Tyre); constructor() { // OK: constructor body this.radio = inject(Radio); } } ``` It is also legal to call `inject` from a provider's factory: ``` providers: [ {provide: Car, useFactory: () => { // OK: a class factory const engine = inject(Engine); return new Car(engine); }} ] ``` Calls to the `inject()` function outside of the class creation or `runInContext` will result in error. Most notably, calls to `inject()` are disallowed after a class instance was created, in methods (including lifecycle hooks): ``` @Component({ ... }) export class CarComponent { ngOnInit() { // ERROR: too late, the component instance was already created const engine = inject(Engine); engine.start(); } } ``` Debugging the error ------------------- Work backwards from the stack trace of the error to identify a place where the disallowed call to `inject()` is located. To fix the error move the `inject()` call to an allowed place (usually a class constructor or a field initializer). angular NG01203: You must register an `NgValueAccessor` with a custom form control NG01203: You must register an `NgValueAccessor` with a custom form control ========================================================================== Description ----------- For all custom form controls, you must register a value accessor. Here's an example of how to provide one: ``` providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MyInputField), multi: true, } ] ``` Debugging the error ------------------- As described above, your control was expected to have a value accessor, but was missing one. However, there are many different reasons this can happen in practice. Here's a listing of some known problems leading to this error. 1. If you **defined** a custom form control, did you remember to provide a value accessor? 2. Did you put `[ngModel](../api/forms/ngmodel)` on an element with no value, or an **invalid element** (e.g. `<div [([ngModel](../api/forms/ngmodel))]="foo">`)? 3. Are you using a custom form control declared inside an `[NgModule](../api/core/ngmodule)`? if so, make sure you are **importing** the `[NgModule](../api/core/ngmodule)`. 4. Are you using `[ngModel](../api/forms/ngmodel)` with a third-party custom form control? Check whether that control provides a value accessor. If not, use **`[ngDefaultControl](../api/forms/defaultvalueaccessor)`** on the control's element. 5. Are you **testing** a custom form control? Be sure to configure your testbed to know about the control. You can do so with `Testbed.configureTestingModule`. 6. Are you using **Nx and Module Federation** with Webpack? Your `webpack.config.js` may require [extra configuration](https://github.com/angular/angular/issues/43821#issuecomment-1054845431) to ensure the forms package is shared. angular NG2009: Component selector does not match shadow DOM requirements NG2009: Component selector does not match shadow DOM requirements ================================================================= Description ----------- The selector of a component using `[ViewEncapsulation.ShadowDom](../api/core/viewencapsulation#ShadowDom)` doesn't match the custom element tag name requirements. In order for a tag name to be considered a valid custom element name, it has to: * Be in lower case. * Contain a hyphen. * Start with a letter (a-z). Debugging the error ------------------- Rename your component's selector so that it matches the requirements. **Before:** ``` @Component({ selector: 'comp', encapsulation: ViewEncapsulation.ShadowDom … }) ``` **After:** ``` @Component({ selector: 'app-comp', encapsulation: ViewEncapsulation.ShadowDom … }) ``` angular NG8003: No directive found with export NG8003: No directive found with export ====================================== Description ----------- Angular can't find a directive with `{{ PLACEHOLDER }}` export name. This is common with a missing import or a missing [`exportAs`](../api/core/directive#exportAs) on a directive. > This is the compiler equivalent of a common runtime error [NG0301: Export Not Found](https://angular.io/errors/errors/NG0301). > > Debugging the error ------------------- Use the string name of the export not found to trace the templates or modules using this export. Ensure that all dependencies are properly imported and declared in our Modules. For example, if the export not found is `[ngForm](../api/forms/ngform)`, we will need to import `[FormsModule](../api/forms/formsmodule)` and declare it in our list of imports in `*.module.ts` to resolve the missing export error. ``` import { FormsModule } from '@angular/forms'; @NgModule({ … imports: [ FormsModule, … ``` If you recently added an import, you will need to restart your server to see these changes. angular NG8002: Unknown attribute or input NG8002: Unknown attribute or input ================================== Description ----------- An attribute or property cannot be resolved during compilation. This error arises when attempting to bind to a property that does not exist. Any property binding must correspond to either: * A native property on the HTML element, or * An `@[Input](../api/core/input)()` property of a component or directive applied to the element. The runtime error for this is `NG0304: '${tagName}' is not a known element: &hellip;'`. Debugging the error ------------------- Look at documentation for the specific [binding syntax](../guide/binding-syntax) used. This is usually a typo or incorrect import. There may also be a missing direction with property selector 'name' or missing input. angular NG01003: Async validator must return a Promise or Observable NG01003: Async validator must return a Promise or Observable ============================================================ Description ----------- Async validators must return a promise or an observable, and emit/resolve them whether the validation fails or succeeds. In particular, they must implement the [AsyncValidatorFn API](../api/forms/asyncvalidator) ``` export function isTenAsync(control: AbstractControl): Observable<ValidationErrors | null> { const v: number = control.value; if (v !== 10) { // Emit an object with a validation error. return of({ 'notTen': true, 'requiredValue': 10 }); } // Emit null, to indicate no error occurred. return of(null); } ``` Debugging the error ------------------- Did you mistakenly use a synchronous validator instead of an async validator? angular NG0209: Expected provider to be `multi: true` but did not get an Array NG0209: Expected provider to be `multi: true` but did not get an Array ====================================================================== Description ----------- The Angular runtime will throw this error when it injects a token intended to be used with `multi: true` but a non-Array was found instead. For example, `[ENVIRONMENT\_INITIALIZER](../api/core/environment_initializer)` should be provided like `{provide: [ENVIRONMENT\_INITIALIZER](../api/core/environment_initializer), multi: true, useValue: () => {...}}`. Debugging the error ------------------- angular NG2003: No suitable injection token for parameter NG2003: No suitable injection token for parameter ================================================= Description ----------- There is no injection token for a constructor parameter at compile time. [InjectionTokens](../api/core/injectiontoken) are tokens that can be used in a Dependency Injection Provider. Debugging the error ------------------- Look at the parameter that throws the error, and all uses of the class. This error is commonly thrown when a constructor defines parameters with primitive types such as `string`, `number`, `boolean`, and `Object`. Use the `@[Injectable](../api/core/injectable)` method or `@[Inject](../api/core/inject)` decorator from `@angular/core` to ensure that the type you are injecting is reified (has a runtime representation). Make sure to add a provider to this decorator so that you do not throw [NG0201: No Provider Found](https://angular.io/errors/errors/NG0201). angular NG0301: Export not found! NG0301: Export not found! ========================= Description ----------- Angular can't find a directive with `{{ PLACEHOLDER }}` export name. The export name is specified in the `exportAs` property of the directive decorator. This is common when using FormsModule or Material modules in templates and you've forgotten to [import the corresponding modules](../guide/sharing-ngmodules). > This is the runtime equivalent of a common compiler error [NG8003: No directive found with export](https://angular.io/errors/errors/NG8003). > > Debugging the error ------------------- Use the export name to trace the templates or modules using this export. Ensure that all dependencies are [properly imported and declared in your NgModules](../guide/sharing-ngmodules). For example, if the export not found is `[ngForm](../api/forms/ngform)`, we need to import `[FormsModule](../api/forms/formsmodule)` and declare it in the list of imports in `*.module.ts` to resolve the error. ``` import { FormsModule } from '@angular/forms'; @NgModule({ … imports: [ FormsModule, … ``` If you recently added an import, you may need to restart your server to see these changes. angular NG0403: An NgModule that was used for bootstrapping does not specify which component should be initialized. NG0403: An NgModule that was used for bootstrapping does not specify which component should be initialized. =========================================================================================================== Description ----------- This error means that an NgModule that was used for bootstrapping an application is missing key information for Angular to proceed with the bootstrap process. The error happens when the NgModule `bootstrap` property is missing (or is an empty array) in the `@[NgModule](../api/core/ngmodule)` annotation and there is no `ngDoBootstrap` lifecycle hook defined on that NgModule class. More information about the bootstrapping process can be found in [this guide](../guide/bootstrapping). The following examples will trigger the error. ``` @NgModule({ declarations: [AppComponent], imports: [BrowserModule, AppRoutingModule], providers: [], }) export class AppModule {} // The `AppModule` is used for bootstrapping, but the `@NgModule.bootstrap` field is missing. platformBrowser().bootstrapModule(AppModule); ``` ``` @NgModule({ declarations: [AppComponent], imports: [BrowserModule, AppRoutingModule], providers: [], bootstrap: [], }) export class AppModule {} // The `AppModule` is used for bootstrapping, but the `@NgModule.bootstrap` field contains an empty array. platformBrowser().bootstrapModule(AppModule); ``` Debugging the error ------------------- Please make sure that the NgModule that is used for bootstrapping is setup correctly: * either the `bootstrap` property exists (and contains a non-empty array) in the `@[NgModule](../api/core/ngmodule)` annotation * or the `ngDoBootstrap` method exists on the NgModule class
programming_docs
angular NG0100: Expression has changed after it was checked NG0100: Expression has changed after it was checked =================================================== Description ----------- Angular throws an `ExpressionChangedAfterItHasBeenCheckedError` when an expression value has been changed after change detection has completed. Angular only throws this error in development mode. In development mode, Angular performs an additional check after each change detection run, to ensure the bindings haven't changed. This catches errors where the view is left in an inconsistent state. This can occur, for example, if a method or getter returns a different value each time it is called, or if a child component changes values on its parent. If either of these occurs, this is a sign that change detection is not stabilized. Angular throws the error to ensure data is always reflected correctly in the view, which prevents erratic UI behavior or a possible infinite loop. This error commonly occurs when you've added template expressions or have begun to implement lifecycle hooks like `ngAfterViewInit` or `ngOnChanges`. It is also common when dealing with loading status and asynchronous operations, or when a child component changes its parent bindings. Debugging the error ------------------- The [source maps](https://developer.mozilla.org/docs/Tools/Debugger/How_to/Use_a_source_map) generated by the CLI are very useful when debugging. Navigate up the call stack until you find a template expression where the value displayed in the error has changed. Ensure that there are no changes to the bindings in the template after change detection is run. This often means refactoring to use the correct [component lifecycle hook](../guide/lifecycle-hooks) for your use case. If the issue exists within `ngAfterViewInit`, the recommended solution is to use a constructor or `ngOnInit` to set initial values, or use `ngAfterContentInit` for other value bindings. If you are binding to methods in the view, ensure that the invocation does not update any of the other bindings in the template. Read more about which solution is right for you in ['Everything you need to know about the "ExpressionChangedAfterItHasBeenCheckedError" error'](https://indepth.dev/posts/1001/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error) and why this is useful at ['Angular Debugging "Expression has changed after it was checked": Simple Explanation (and Fix)'](https://blog.angular-university.io/angular-debugging). angular NG0910: Unsafe bindings on an iframe element NG0910: Unsafe bindings on an iframe element ============================================ Description ----------- You see this error when Angular detects an attribute binding or a property binding on an `<iframe>` element using the following property names: * sandbox * allow * allowFullscreen * referrerPolicy * csp * fetchPriority The mentioned attributes affect the security model setup for `<iframe>`s and it's important to apply them before setting the `src` or `srcdoc` attributes. To enforce that, Angular requires these attributes to be set on `<iframe>`s as static attributes, so the values are set at the element creation time and they remain the same throughout the lifetime of an `<iframe>` instance. The error is thrown when a property binding with one of the mentioned attribute names is used: ``` <iframe [sandbox]="'allow-scripts'" src="..."></iframe> ``` or when it's an attribute bindings: ``` <iframe [attr.sandbox]="'allow-scripts'" src="..."></iframe> ``` Also, the error is thrown when a similar pattern is used in Directive's host bindings: ``` @Directive({ selector: 'iframe', host: { '[sandbox]': `'allow-scripts'`, '[attr.sandbox]': `'allow-scripts'`, } }) class IframeDirective {} ``` Debugging the error ------------------- The error message includes the name of the component with the template where an `<iframe>` element with unsafe bindings is located. The recommended solution is to use the mentioned attributes as static ones, for example: ``` <iframe sandbox="allow-scripts" src="..."></iframe> ``` If you need to have different values for these attributes (depending on various conditions), you can use an `*[ngIf](../api/common/ngif)` or an `*[ngSwitch](../api/common/ngswitch)` on an `<iframe>` element: ``` <iframe *ngIf="someConditionA" sandbox="allow-scripts" src="..."></iframe> <iframe *ngIf="someConditionB" sandbox="allow-forms" src="..."></iframe> <iframe *ngIf="someConditionC" sandbox="allow-popups" src="..."></iframe> ``` angular NG3003: Import cycles would need to be created to compile this component NG3003: Import cycles would need to be created to compile this component ======================================================================== Description ----------- A component, directive, or pipe that is referenced by this component would require the compiler to add an import that would lead to a cycle of imports. For example, consider a scenario where a `ParentComponent` references a `ChildComponent` in its template: ``` import { Component } from '@angular/core'; @Component({selector: 'app-parent', template: '<app-child></app-child>'}) export class ParentComponent {} ``` ``` import { Component } from '@angular/core'; import { ParentComponent } from './parent.component'; @Component({selector: 'app-child', template: 'The child!'}) export class ChildComponent { constructor(private parent: ParentComponent) {} } ``` There is already an import from `child.component.ts` to `parent.component.ts` since the `ChildComponent` references the `ParentComponent` in its constructor. > **NOTE**: The parent component's template contains `<child></child>`. The generated code for this template must therefore contain a reference to the `ChildComponent` class. In order to make this reference, the compiler would have to add an import from `parent.component.ts` to `child.component.ts`, which would cause an import cycle: > > > ``` > parent.component.ts -> child.component.ts -> parent.component.ts > ``` > ### Remote Scoping To avoid adding imports that create cycles, additional code is added to the `[NgModule](../api/core/ngmodule)` class where the component that wires up the dependencies is declared. This is known as "remote scoping". ### Libraries Unfortunately, "remote scoping" code is side-effectful —which prevents tree shaking— and cannot be used in libraries. So when building libraries using the `"compilationMode": "partial"` setting, any component that would require a cyclic import will cause this `NG3003` compiler error to be raised. Debugging the error ------------------- The cycle that would be generated is shown as part of the error message. For example: ``` The component ChildComponent is used in the template but importing it would create a cycle: /parent.component.ts -> /child.component.ts -> /parent.component.ts ``` Use this to identify how the referenced component, pipe, or directive has a dependency back to the component being compiled. Here are some ideas for fixing the problem: * Try to rearrange your dependencies to avoid the cycle. For example, using an intermediate interface that is stored in an independent file that can be imported to both dependent files without causing an import cycle. * Move the classes that reference each other into the same file, to avoid any imports between them. * Convert import statements to type-only imports (using `import type` syntax) if the imported declarations are only used as types, as type-only imports do not contribute to cycles. angular NG0300: Multiple components match with the same tagname NG0300: Multiple components match with the same tagname ======================================================= Description ----------- Two or more components use the same [element selector](../guide/component-overview#specifying-a-components-css-selector). Because there can only be a single component associated with an element, selectors must be unique strings to prevent ambiguity for Angular. Debugging the error ------------------- Use the element name from the error message to search for places where you're using the same [selector declaration](../guide/architecture-components) in your codebase: ``` @Component({ selector: 'YOUR_STRING', … }) ``` Ensure that each component has a unique CSS selector. This will guarantee that Angular renders the component you expect. If you're having trouble finding multiple components with this selector tag name, check for components from imported component libraries, such as Angular Material. Make sure you're following the [best practices](../guide/styleguide#component-selectors) for your selectors to prevent collisions. angular NG0302: Pipe not found! NG0302: Pipe not found! ======================= Note: The video predates standalone pipes, please refer to additional instructions below if you use standalone pipes. Description ----------- Angular can't find a pipe with this name. The pipe referenced in the template has not been named or declared properly. In order for a [pipe](../guide/pipes) to be used: * it must be declared as a part of an `[NgModule](../api/core/ngmodule)` (added to the `declarations` array) or marked as standalone (by adding the `standalone: true` flag to the Pipe decorator). * it must be imported in an `[NgModule](../api/core/ngmodule)` or a standalone component where it is used. * the name used in a template must match the name defined in the Pipe decorator. Debugging the error ------------------- Use the pipe name to trace where the pipe is declared and used. To resolve this error, ensure that: * If the pipe is local to the `[NgModule](../api/core/ngmodule)`, it is uniquely named in the pipe's decorator and declared in the `[NgModule](../api/core/ngmodule)`. * If the pipe is standalone or from another `[NgModule](../api/core/ngmodule)`, it is added to the `imports` field of the current `[NgModule](../api/core/ngmodule)` or standalone component. If you recently added an import or declaration, you may need to restart your server to see these changes. angular NG02200: Cannot find a differ for object in ngFor NG02200: Cannot find a differ for object in ngFor ================================================= Description ----------- `[NgFor](../api/common/ngfor)` could not find an iterable differ for the value passed in. Make sure it's an iterable, like an `Array`. Debugging the error ------------------- When using ngFor in a template, you must use some type of Iterable, like `Array`, `Set`, `Map`, etc. If you're trying to iterate over the keys in an object, you should look at the [KeyValue pipe](../api/common/keyvaluepipe) instead. angular NG6999: Invalid @NgModule() metadata NG6999: Invalid @NgModule() metadata ==================================== Description ----------- This error represents the import or export of an `@[NgModule](../api/core/ngmodule)()` that doesn't have valid metadata. Debugging the error ------------------- The library might have been processed with `ngcc`. If this is the case, try removing and reinstalling `node_modules`. This error is likely due to the library being published for Angular Ivy, which cannot be used in this View Engine application. If that is not the case then it might be a View Engine based library that was converted to Ivy by ngcc during a postinstall step. Check the peer dependencies to ensure that you're using a compatible version of Angular. angular NG1001: Decorator argument is not an object literal NG1001: Decorator argument is not an object literal =================================================== Description ----------- To make the metadata extraction in the Angular compiler faster, the decorators `@[NgModule](../api/core/ngmodule)`, `@[Pipe](../api/core/pipe)`, `@[Component](../api/core/component)`, `@[Directive](../api/core/directive)`, and `@[Injectable](../api/core/injectable)` accept only object literals as arguments. This is an [intentional change in Ivy](https://github.com/angular/angular/issues/30840#issuecomment-498869540), which enforces stricter argument requirements for decorators than View Engine. Ivy requires this approach because it compiles decorators by moving the expressions into other locations in the class output. Debugging the error ------------------- Move all declarations: ``` const moduleDefinition = {…} @NgModule(moduleDefinition) export class AppModule { constructor() {} } ``` into the decorator: ``` @NgModule({…}) export class AppModule { constructor() {} } ``` angular NG0201: No provider for {token} found! NG0201: No provider for {token} found! ====================================== Description ----------- You see this error when you try to inject a service but have not declared a corresponding provider. A provider is a mapping that supplies a value that you can inject into the constructor of a class in your application. Read more on providers in our [Dependency Injection guide](../guide/dependency-injection). Debugging the error ------------------- Work backwards from the object where the error states that a [provider](../guide/architecture-services) is missing: `No provider for ${this}!`. This is commonly thrown in [services](../tutorial/tour-of-heroes/toh-pt4), which require non-existing providers. To fix the error ensure that your service is registered in the list of providers of an `[NgModule](../api/core/ngmodule)` or has the `@[Injectable](../api/core/injectable)` decorator with a `providedIn` property at top. The most common solution is to add a provider in `@[Injectable](../api/core/injectable)` using `providedIn`: ``` @Injectable({ providedIn: 'app' }) ``` angular NG8001: Unknown HTML element or component NG8001: Unknown HTML element or component ========================================= Description ----------- One or more elements cannot be resolved during compilation because the element is not defined by the HTML spec, or there is no component or directive with such element selector. > This is the compiler equivalent of a common runtime error `NG0304: '${tagName}' is not a known element: ...`. > > Debugging the error ------------------- Use the element name in the error to find the file(s) where the element is being used. Check that the name and selector are correct. Make sure that the component is correctly imported inside your NgModule or standalone component, by checking its presence in the `imports` field. If the component is declared in an NgModule (meaning that it is not standalone) make sure that it is exported correctly from it, by checking its presence in the `exports` field. When using custom elements or web components, ensure that you add [`CUSTOM_ELEMENTS_SCHEMA`](../api/core/custom_elements_schema) to the application module. If this does not resolve the error, check the imported libraries for any recent changes to the exports and properties you are using, and restart your server. angular NG6100: Setting NgModule.id to module.id is a common anti-pattern NG6100: Setting NgModule.id to module.id is a common anti-pattern ================================================================= Description ----------- Using `module.id` as an NgModule `id` is a common anti-pattern and is likely not serving a useful purpose in your code. NgModules can be declared with an `id`: ``` @NgModule({ id: 'my_module' }) export class MyModule {} ``` Declaring an `id` makes the NgModule available for lookup via the `[getNgModuleById](../api/core/getngmodulebyid)()` operation. This functionality is rarely used, mainly in very specific bundling scenarios when lazily loading NgModules without obtaining direct references to them. In most Angular code, ES dynamic `import()` (`import('./path/to/module')`) should be used instead, as this provides a direct reference to the NgModule being loaded without the need for a global registration side effect. If you are not using `[getNgModuleById](../api/core/getngmodulebyid)`, you do not need to provide `id`s for your NgModules. Providing one has a significant drawback: it makes the NgModule non-tree-shakable, which can have an impact on your bundle size. In particular, the pattern of specifying `id: module.id` results from a misunderstanding of `@[NgModule.id](../api/core/ngmodule#id)`. In earlier versions of Angular, it was sometimes necessary to include the property `moduleId: module.id` in `@[Component](../api/core/component)` metadata. Using `module.id` for `@[NgModule.id](../api/core/ngmodule#id)` likely results from confusion between `@[Component.moduleId](../api/core/component#moduleId)` and `@[NgModule.id](../api/core/ngmodule#id)`. `module.id` would not typically be useful for `[getNgModuleById](../api/core/getngmodulebyid)()` operations as the `id` needs to be a well-known string, and `module.id` is usually opaque to consumers. Debugging the error ------------------- You can remove the `id: module.id` declaration from your NgModules. The compiler ignores this declaration and issues this warning instead. angular NG0200: Circular dependency in DI detected while instantiating a provider NG0200: Circular dependency in DI detected while instantiating a provider ========================================================================= Description ----------- A cyclic dependency exists when a [dependency of a service](../guide/hierarchical-dependency-injection) directly or indirectly depends on the service itself. For example, if `UserService` depends on `EmployeeService`, which also depends on `UserService`. Angular will have to instantiate `EmployeeService` to create `UserService`, which depends on `UserService`, itself. Debugging the error ------------------- Use the call stack to determine where the cyclical dependency exists. You will be able to see if any child dependencies rely on the original file by [mapping out](../guide/dependency-injection-in-action) the component, module, or service's dependencies, and identifying the loop causing the problem. Break this loop (or circle) of dependency to resolve this error. This most commonly means removing or refactoring the dependencies to not be reliant on one another. symfony Namespaces Namespaces ========== Symfony ------- * [Symfony](https://api.symfony.com/4.1/Symfony.html) * [Symfony\Bridge](symfony/bridge) * [Symfony\Bridge\Doctrine](symfony/bridge/doctrine) * [Symfony\Bridge\Doctrine\CacheWarmer](symfony/bridge/doctrine/cachewarmer) * [Symfony\Bridge\Doctrine\DataCollector](symfony/bridge/doctrine/datacollector) * [Symfony\Bridge\Doctrine\DataFixtures](symfony/bridge/doctrine/datafixtures) * [Symfony\Bridge\Doctrine\DependencyInjection](symfony/bridge/doctrine/dependencyinjection) * [Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass](symfony/bridge/doctrine/dependencyinjection/compilerpass) * [Symfony\Bridge\Doctrine\DependencyInjection\Security](symfony/bridge/doctrine/dependencyinjection/security) * [Symfony\Bridge\Doctrine\DependencyInjection\Security\UserProvider](symfony/bridge/doctrine/dependencyinjection/security/userprovider) * [Symfony\Bridge\Doctrine\Form](symfony/bridge/doctrine/form) * [Symfony\Bridge\Doctrine\Form\ChoiceList](symfony/bridge/doctrine/form/choicelist) * [Symfony\Bridge\Doctrine\Form\DataTransformer](symfony/bridge/doctrine/form/datatransformer) * [Symfony\Bridge\Doctrine\Form\EventListener](symfony/bridge/doctrine/form/eventlistener) * [Symfony\Bridge\Doctrine\Form\Type](symfony/bridge/doctrine/form/type) * [Symfony\Bridge\Doctrine\Logger](symfony/bridge/doctrine/logger) * [Symfony\Bridge\Doctrine\Messenger](symfony/bridge/doctrine/messenger) * [Symfony\Bridge\Doctrine\PropertyInfo](symfony/bridge/doctrine/propertyinfo) * [Symfony\Bridge\Doctrine\Security](symfony/bridge/doctrine/security) * [Symfony\Bridge\Doctrine\Security\RememberMe](symfony/bridge/doctrine/security/rememberme) * [Symfony\Bridge\Doctrine\Security\User](symfony/bridge/doctrine/security/user) * [Symfony\Bridge\Doctrine\Test](symfony/bridge/doctrine/test) * [Symfony\Bridge\Doctrine\Validator](symfony/bridge/doctrine/validator) * [Symfony\Bridge\Doctrine\Validator\Constraints](symfony/bridge/doctrine/validator/constraints) * [Symfony\Bridge\Monolog](symfony/bridge/monolog) * [Symfony\Bridge\Monolog\Formatter](symfony/bridge/monolog/formatter) * [Symfony\Bridge\Monolog\Handler](symfony/bridge/monolog/handler) * [Symfony\Bridge\Monolog\Handler\FingersCrossed](symfony/bridge/monolog/handler/fingerscrossed) * [Symfony\Bridge\Monolog\Processor](symfony/bridge/monolog/processor) * [Symfony\Bridge\PhpUnit](symfony/bridge/phpunit) * [Symfony\Bridge\PhpUnit\Legacy](symfony/bridge/phpunit/legacy) * [Symfony\Bridge\PhpUnit\TextUI](symfony/bridge/phpunit/textui) * [Symfony\Bridge\ProxyManager](symfony/bridge/proxymanager) * [Symfony\Bridge\ProxyManager\LazyProxy](symfony/bridge/proxymanager/lazyproxy) * [Symfony\Bridge\ProxyManager\LazyProxy\Instantiator](symfony/bridge/proxymanager/lazyproxy/instantiator) * [Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper](symfony/bridge/proxymanager/lazyproxy/phpdumper) * [Symfony\Bridge\Twig](symfony/bridge/twig) * [Symfony\Bridge\Twig\Command](symfony/bridge/twig/command) * [Symfony\Bridge\Twig\DataCollector](symfony/bridge/twig/datacollector) * [Symfony\Bridge\Twig\Extension](symfony/bridge/twig/extension) * [Symfony\Bridge\Twig\Form](symfony/bridge/twig/form) * [Symfony\Bridge\Twig\Node](symfony/bridge/twig/node) * [Symfony\Bridge\Twig\NodeVisitor](symfony/bridge/twig/nodevisitor) * [Symfony\Bridge\Twig\TokenParser](symfony/bridge/twig/tokenparser) * [Symfony\Bridge\Twig\Translation](symfony/bridge/twig/translation) * [Symfony\Bundle](symfony/bundle) * [Symfony\Bundle\DebugBundle](symfony/bundle/debugbundle) * [Symfony\Bundle\DebugBundle\Command](symfony/bundle/debugbundle/command) * [Symfony\Bundle\DebugBundle\DependencyInjection](symfony/bundle/debugbundle/dependencyinjection) * [Symfony\Bundle\DebugBundle\DependencyInjection\Compiler](symfony/bundle/debugbundle/dependencyinjection/compiler) * [Symfony\Bundle\FrameworkBundle](symfony/bundle/frameworkbundle) * [Symfony\Bundle\FrameworkBundle\CacheWarmer](symfony/bundle/frameworkbundle/cachewarmer) * [Symfony\Bundle\FrameworkBundle\Command](symfony/bundle/frameworkbundle/command) * [Symfony\Bundle\FrameworkBundle\Console](symfony/bundle/frameworkbundle/console) * [Symfony\Bundle\FrameworkBundle\Console\Descriptor](symfony/bundle/frameworkbundle/console/descriptor) * [Symfony\Bundle\FrameworkBundle\Console\Helper](symfony/bundle/frameworkbundle/console/helper) * [Symfony\Bundle\FrameworkBundle\Controller](symfony/bundle/frameworkbundle/controller) * [Symfony\Bundle\FrameworkBundle\DataCollector](symfony/bundle/frameworkbundle/datacollector) * [Symfony\Bundle\FrameworkBundle\DependencyInjection](symfony/bundle/frameworkbundle/dependencyinjection) * [Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler](symfony/bundle/frameworkbundle/dependencyinjection/compiler) * [Symfony\Bundle\FrameworkBundle\EventListener](symfony/bundle/frameworkbundle/eventlistener) * [Symfony\Bundle\FrameworkBundle\HttpCache](symfony/bundle/frameworkbundle/httpcache) * [Symfony\Bundle\FrameworkBundle\Kernel](symfony/bundle/frameworkbundle/kernel) * [Symfony\Bundle\FrameworkBundle\Routing](symfony/bundle/frameworkbundle/routing) * [Symfony\Bundle\FrameworkBundle\Templating](symfony/bundle/frameworkbundle/templating) * [Symfony\Bundle\FrameworkBundle\Templating\Helper](symfony/bundle/frameworkbundle/templating/helper) * [Symfony\Bundle\FrameworkBundle\Templating\Loader](symfony/bundle/frameworkbundle/templating/loader) * [Symfony\Bundle\FrameworkBundle\Test](symfony/bundle/frameworkbundle/test) * [Symfony\Bundle\FrameworkBundle\Translation](symfony/bundle/frameworkbundle/translation) * [Symfony\Bundle\SecurityBundle](symfony/bundle/securitybundle) * [Symfony\Bundle\SecurityBundle\CacheWarmer](symfony/bundle/securitybundle/cachewarmer) * [Symfony\Bundle\SecurityBundle\Command](symfony/bundle/securitybundle/command) * [Symfony\Bundle\SecurityBundle\DataCollector](symfony/bundle/securitybundle/datacollector) * [Symfony\Bundle\SecurityBundle\Debug](symfony/bundle/securitybundle/debug) * [Symfony\Bundle\SecurityBundle\DependencyInjection](symfony/bundle/securitybundle/dependencyinjection) * [Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler](symfony/bundle/securitybundle/dependencyinjection/compiler) * [Symfony\Bundle\SecurityBundle\DependencyInjection\Security](symfony/bundle/securitybundle/dependencyinjection/security) * [Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory](symfony/bundle/securitybundle/dependencyinjection/security/factory) * [Symfony\Bundle\SecurityBundle\DependencyInjection\Security\UserProvider](symfony/bundle/securitybundle/dependencyinjection/security/userprovider) * [Symfony\Bundle\SecurityBundle\EventListener](symfony/bundle/securitybundle/eventlistener) * [Symfony\Bundle\SecurityBundle\Security](symfony/bundle/securitybundle/security) * [Symfony\Bundle\SecurityBundle\Templating](symfony/bundle/securitybundle/templating) * [Symfony\Bundle\SecurityBundle\Templating\Helper](symfony/bundle/securitybundle/templating/helper) * [Symfony\Bundle\TwigBundle](symfony/bundle/twigbundle) * [Symfony\Bundle\TwigBundle\CacheWarmer](symfony/bundle/twigbundle/cachewarmer) * [Symfony\Bundle\TwigBundle\Command](symfony/bundle/twigbundle/command) * [Symfony\Bundle\TwigBundle\Controller](symfony/bundle/twigbundle/controller) * [Symfony\Bundle\TwigBundle\DependencyInjection](symfony/bundle/twigbundle/dependencyinjection) * [Symfony\Bundle\TwigBundle\DependencyInjection\Compiler](symfony/bundle/twigbundle/dependencyinjection/compiler) * [Symfony\Bundle\TwigBundle\DependencyInjection\Configurator](symfony/bundle/twigbundle/dependencyinjection/configurator) * [Symfony\Bundle\TwigBundle\Loader](symfony/bundle/twigbundle/loader) * [Symfony\Bundle\WebProfilerBundle](symfony/bundle/webprofilerbundle) * [Symfony\Bundle\WebProfilerBundle\Controller](symfony/bundle/webprofilerbundle/controller) * [Symfony\Bundle\WebProfilerBundle\Csp](symfony/bundle/webprofilerbundle/csp) * [Symfony\Bundle\WebProfilerBundle\DependencyInjection](symfony/bundle/webprofilerbundle/dependencyinjection) * [Symfony\Bundle\WebProfilerBundle\EventListener](symfony/bundle/webprofilerbundle/eventlistener) * [Symfony\Bundle\WebProfilerBundle\Profiler](symfony/bundle/webprofilerbundle/profiler) * [Symfony\Bundle\WebProfilerBundle\Twig](symfony/bundle/webprofilerbundle/twig) * [Symfony\Bundle\WebServerBundle](symfony/bundle/webserverbundle) * [Symfony\Bundle\WebServerBundle\Command](symfony/bundle/webserverbundle/command) * [Symfony\Bundle\WebServerBundle\DependencyInjection](symfony/bundle/webserverbundle/dependencyinjection) * [Symfony\Component](symfony/component) * [Symfony\Component\Asset](symfony/component/asset) * [Symfony\Component\Asset\Context](symfony/component/asset/context) * [Symfony\Component\Asset\Exception](symfony/component/asset/exception) * [Symfony\Component\Asset\VersionStrategy](symfony/component/asset/versionstrategy) * [Symfony\Component\BrowserKit](symfony/component/browserkit) * [Symfony\Component\BrowserKit\Exception](symfony/component/browserkit/exception) * [Symfony\Component\Cache](symfony/component/cache) * [Symfony\Component\Cache\Adapter](symfony/component/cache/adapter) * [Symfony\Component\Cache\DataCollector](symfony/component/cache/datacollector) * [Symfony\Component\Cache\Exception](symfony/component/cache/exception) * [Symfony\Component\Cache\Simple](symfony/component/cache/simple) * [Symfony\Component\Cache\Traits](symfony/component/cache/traits) * [Symfony\Component\Config](symfony/component/config) * [Symfony\Component\Config\Definition](symfony/component/config/definition) * [Symfony\Component\Config\Definition\Builder](symfony/component/config/definition/builder) * [Symfony\Component\Config\Definition\Dumper](symfony/component/config/definition/dumper) * [Symfony\Component\Config\Definition\Exception](symfony/component/config/definition/exception) * [Symfony\Component\Config\Exception](symfony/component/config/exception) * [Symfony\Component\Config\Loader](symfony/component/config/loader) * [Symfony\Component\Config\Resource](symfony/component/config/resource) * [Symfony\Component\Config\Util](symfony/component/config/util) * [Symfony\Component\Config\Util\Exception](symfony/component/config/util/exception) * [Symfony\Component\Console](symfony/component/console) * [Symfony\Component\Console\Command](symfony/component/console/command) * [Symfony\Component\Console\CommandLoader](symfony/component/console/commandloader) * [Symfony\Component\Console\DependencyInjection](symfony/component/console/dependencyinjection) * [Symfony\Component\Console\Descriptor](symfony/component/console/descriptor) * [Symfony\Component\Console\Event](symfony/component/console/event) * [Symfony\Component\Console\EventListener](symfony/component/console/eventlistener) * [Symfony\Component\Console\Exception](symfony/component/console/exception) * [Symfony\Component\Console\Formatter](symfony/component/console/formatter) * [Symfony\Component\Console\Helper](symfony/component/console/helper) * [Symfony\Component\Console\Input](symfony/component/console/input) * [Symfony\Component\Console\Logger](symfony/component/console/logger) * [Symfony\Component\Console\Output](symfony/component/console/output) * [Symfony\Component\Console\Question](symfony/component/console/question) * [Symfony\Component\Console\Style](symfony/component/console/style) * [Symfony\Component\Console\Tester](symfony/component/console/tester) * [Symfony\Component\CssSelector](symfony/component/cssselector) * [Symfony\Component\CssSelector\Exception](symfony/component/cssselector/exception) * [Symfony\Component\CssSelector\Node](symfony/component/cssselector/node) * [Symfony\Component\CssSelector\Parser](symfony/component/cssselector/parser) * [Symfony\Component\CssSelector\Parser\Handler](symfony/component/cssselector/parser/handler) * [Symfony\Component\CssSelector\Parser\Shortcut](symfony/component/cssselector/parser/shortcut) * [Symfony\Component\CssSelector\Parser\Tokenizer](symfony/component/cssselector/parser/tokenizer) * [Symfony\Component\CssSelector\XPath](symfony/component/cssselector/xpath) * [Symfony\Component\CssSelector\XPath\Extension](symfony/component/cssselector/xpath/extension) * [Symfony\Component\Debug](symfony/component/debug) * [Symfony\Component\Debug\Exception](symfony/component/debug/exception) * [Symfony\Component\Debug\FatalErrorHandler](symfony/component/debug/fatalerrorhandler) * [Symfony\Component\DependencyInjection](symfony/component/dependencyinjection) * [Symfony\Component\DependencyInjection\Argument](symfony/component/dependencyinjection/argument) * [Symfony\Component\DependencyInjection\Compiler](symfony/component/dependencyinjection/compiler) * [Symfony\Component\DependencyInjection\Config](symfony/component/dependencyinjection/config) * [Symfony\Component\DependencyInjection\Dumper](symfony/component/dependencyinjection/dumper) * [Symfony\Component\DependencyInjection\Exception](symfony/component/dependencyinjection/exception) * [Symfony\Component\DependencyInjection\Extension](symfony/component/dependencyinjection/extension) * [Symfony\Component\DependencyInjection\LazyProxy](symfony/component/dependencyinjection/lazyproxy) * [Symfony\Component\DependencyInjection\LazyProxy\Instantiator](symfony/component/dependencyinjection/lazyproxy/instantiator) * [Symfony\Component\DependencyInjection\LazyProxy\PhpDumper](symfony/component/dependencyinjection/lazyproxy/phpdumper) * [Symfony\Component\DependencyInjection\Loader](symfony/component/dependencyinjection/loader) * [Symfony\Component\DependencyInjection\Loader\Configurator](symfony/component/dependencyinjection/loader/configurator) * [Symfony\Component\DependencyInjection\Loader\Configurator\Traits](symfony/component/dependencyinjection/loader/configurator/traits) * [Symfony\Component\DependencyInjection\ParameterBag](symfony/component/dependencyinjection/parameterbag) * [Symfony\Component\DomCrawler](symfony/component/domcrawler) * [Symfony\Component\DomCrawler\Field](symfony/component/domcrawler/field) * [Symfony\Component\Dotenv](symfony/component/dotenv) * [Symfony\Component\Dotenv\Exception](symfony/component/dotenv/exception) * [Symfony\Component\EventDispatcher](symfony/component/eventdispatcher) * [Symfony\Component\EventDispatcher\Debug](symfony/component/eventdispatcher/debug) * [Symfony\Component\EventDispatcher\DependencyInjection](symfony/component/eventdispatcher/dependencyinjection) * [Symfony\Component\ExpressionLanguage](symfony/component/expressionlanguage) * [Symfony\Component\ExpressionLanguage\Node](symfony/component/expressionlanguage/node) * [Symfony\Component\Filesystem](symfony/component/filesystem) * [Symfony\Component\Filesystem\Exception](symfony/component/filesystem/exception) * [Symfony\Component\Finder](symfony/component/finder) * [Symfony\Component\Finder\Comparator](symfony/component/finder/comparator) * [Symfony\Component\Finder\Exception](symfony/component/finder/exception) * [Symfony\Component\Finder\Iterator](symfony/component/finder/iterator) * [Symfony\Component\Form](symfony/component/form) * [Symfony\Component\Form\ChoiceList](symfony/component/form/choicelist) * [Symfony\Component\Form\ChoiceList\Factory](symfony/component/form/choicelist/factory) * [Symfony\Component\Form\ChoiceList\Loader](symfony/component/form/choicelist/loader) * [Symfony\Component\Form\ChoiceList\View](symfony/component/form/choicelist/view) * [Symfony\Component\Form\Command](symfony/component/form/command) * [Symfony\Component\Form\Console](symfony/component/form/console) * [Symfony\Component\Form\Console\Descriptor](symfony/component/form/console/descriptor) * [Symfony\Component\Form\Console\Helper](symfony/component/form/console/helper) * [Symfony\Component\Form\DependencyInjection](symfony/component/form/dependencyinjection) * [Symfony\Component\Form\Exception](symfony/component/form/exception) * [Symfony\Component\Form\Extension](symfony/component/form/extension) * [Symfony\Component\Form\Extension\Core](symfony/component/form/extension/core) * [Symfony\Component\Form\Extension\Core\DataMapper](symfony/component/form/extension/core/datamapper) * [Symfony\Component\Form\Extension\Core\DataTransformer](symfony/component/form/extension/core/datatransformer) * [Symfony\Component\Form\Extension\Core\EventListener](symfony/component/form/extension/core/eventlistener) * [Symfony\Component\Form\Extension\Core\Type](symfony/component/form/extension/core/type) * [Symfony\Component\Form\Extension\Csrf](symfony/component/form/extension/csrf) * [Symfony\Component\Form\Extension\Csrf\EventListener](symfony/component/form/extension/csrf/eventlistener) * [Symfony\Component\Form\Extension\Csrf\Type](symfony/component/form/extension/csrf/type) * [Symfony\Component\Form\Extension\DataCollector](symfony/component/form/extension/datacollector) * [Symfony\Component\Form\Extension\DataCollector\EventListener](symfony/component/form/extension/datacollector/eventlistener) * [Symfony\Component\Form\Extension\DataCollector\Proxy](symfony/component/form/extension/datacollector/proxy) * [Symfony\Component\Form\Extension\DataCollector\Type](symfony/component/form/extension/datacollector/type) * [Symfony\Component\Form\Extension\DependencyInjection](symfony/component/form/extension/dependencyinjection) * [Symfony\Component\Form\Extension\HttpFoundation](symfony/component/form/extension/httpfoundation) * [Symfony\Component\Form\Extension\HttpFoundation\Type](symfony/component/form/extension/httpfoundation/type) * [Symfony\Component\Form\Extension\Templating](symfony/component/form/extension/templating) * [Symfony\Component\Form\Extension\Validator](symfony/component/form/extension/validator) * [Symfony\Component\Form\Extension\Validator\Constraints](symfony/component/form/extension/validator/constraints) * [Symfony\Component\Form\Extension\Validator\EventListener](symfony/component/form/extension/validator/eventlistener) * [Symfony\Component\Form\Extension\Validator\Type](symfony/component/form/extension/validator/type) * [Symfony\Component\Form\Extension\Validator\Util](symfony/component/form/extension/validator/util) * [Symfony\Component\Form\Extension\Validator\ViolationMapper](symfony/component/form/extension/validator/violationmapper) * [Symfony\Component\Form\Guess](symfony/component/form/guess) * [Symfony\Component\Form\Test](symfony/component/form/test) * [Symfony\Component\Form\Test\Traits](symfony/component/form/test/traits) * [Symfony\Component\Form\Util](symfony/component/form/util) * [Symfony\Component\HttpFoundation](symfony/component/httpfoundation) * [Symfony\Component\HttpFoundation\Exception](symfony/component/httpfoundation/exception) * [Symfony\Component\HttpFoundation\File](symfony/component/httpfoundation/file) * [Symfony\Component\HttpFoundation\File\Exception](symfony/component/httpfoundation/file/exception) * [Symfony\Component\HttpFoundation\File\MimeType](symfony/component/httpfoundation/file/mimetype) * [Symfony\Component\HttpFoundation\Session](symfony/component/httpfoundation/session) * [Symfony\Component\HttpFoundation\Session\Attribute](symfony/component/httpfoundation/session/attribute) * [Symfony\Component\HttpFoundation\Session\Flash](symfony/component/httpfoundation/session/flash) * [Symfony\Component\HttpFoundation\Session\Storage](symfony/component/httpfoundation/session/storage) * [Symfony\Component\HttpFoundation\Session\Storage\Handler](symfony/component/httpfoundation/session/storage/handler) * [Symfony\Component\HttpFoundation\Session\Storage\Proxy](symfony/component/httpfoundation/session/storage/proxy) * [Symfony\Component\HttpKernel](symfony/component/httpkernel) * [Symfony\Component\HttpKernel\Bundle](symfony/component/httpkernel/bundle) * [Symfony\Component\HttpKernel\CacheClearer](symfony/component/httpkernel/cacheclearer) * [Symfony\Component\HttpKernel\CacheWarmer](symfony/component/httpkernel/cachewarmer) * [Symfony\Component\HttpKernel\Config](symfony/component/httpkernel/config) * [Symfony\Component\HttpKernel\Controller](symfony/component/httpkernel/controller) * [Symfony\Component\HttpKernel\ControllerMetadata](symfony/component/httpkernel/controllermetadata) * [Symfony\Component\HttpKernel\Controller\ArgumentResolver](symfony/component/httpkernel/controller/argumentresolver) * [Symfony\Component\HttpKernel\DataCollector](symfony/component/httpkernel/datacollector) * [Symfony\Component\HttpKernel\Debug](symfony/component/httpkernel/debug) * [Symfony\Component\HttpKernel\DependencyInjection](symfony/component/httpkernel/dependencyinjection) * [Symfony\Component\HttpKernel\Event](symfony/component/httpkernel/event) * [Symfony\Component\HttpKernel\EventListener](symfony/component/httpkernel/eventlistener) * [Symfony\Component\HttpKernel\Exception](symfony/component/httpkernel/exception) * [Symfony\Component\HttpKernel\Fragment](symfony/component/httpkernel/fragment) * [Symfony\Component\HttpKernel\HttpCache](symfony/component/httpkernel/httpcache) * [Symfony\Component\HttpKernel\Log](symfony/component/httpkernel/log) * [Symfony\Component\HttpKernel\Profiler](symfony/component/httpkernel/profiler) * [Symfony\Component\Inflector](symfony/component/inflector) * [Symfony\Component\Intl](symfony/component/intl) * [Symfony\Component\Intl\Collator](symfony/component/intl/collator) * [Symfony\Component\Intl\Data](symfony/component/intl/data) * [Symfony\Component\Intl\Data\Bundle](symfony/component/intl/data/bundle) * [Symfony\Component\Intl\Data\Bundle\Compiler](symfony/component/intl/data/bundle/compiler) * [Symfony\Component\Intl\Data\Bundle\Reader](symfony/component/intl/data/bundle/reader) * [Symfony\Component\Intl\Data\Bundle\Writer](symfony/component/intl/data/bundle/writer) * [Symfony\Component\Intl\Data\Generator](symfony/component/intl/data/generator) * [Symfony\Component\Intl\Data\Provider](symfony/component/intl/data/provider) * [Symfony\Component\Intl\Data\Util](symfony/component/intl/data/util) * [Symfony\Component\Intl\DateFormatter](symfony/component/intl/dateformatter) * [Symfony\Component\Intl\DateFormatter\DateFormat](symfony/component/intl/dateformatter/dateformat) * [Symfony\Component\Intl\Exception](symfony/component/intl/exception) * [Symfony\Component\Intl\Globals](symfony/component/intl/globals) * [Symfony\Component\Intl\Locale](symfony/component/intl/locale) * [Symfony\Component\Intl\NumberFormatter](symfony/component/intl/numberformatter) * [Symfony\Component\Intl\ResourceBundle](symfony/component/intl/resourcebundle) * [Symfony\Component\Intl\Util](symfony/component/intl/util) * [Symfony\Component\Ldap](symfony/component/ldap) * [Symfony\Component\Ldap\Adapter](symfony/component/ldap/adapter) * [Symfony\Component\Ldap\Adapter\ExtLdap](symfony/component/ldap/adapter/extldap) * [Symfony\Component\Ldap\Exception](symfony/component/ldap/exception) * [Symfony\Component\Lock](symfony/component/lock) * [Symfony\Component\Lock\Exception](symfony/component/lock/exception) * [Symfony\Component\Lock\Store](symfony/component/lock/store) * [Symfony\Component\Lock\Strategy](symfony/component/lock/strategy) * [Symfony\Component\Messenger](symfony/component/messenger) * [Symfony\Component\Messenger\Asynchronous](symfony/component/messenger/asynchronous) * [Symfony\Component\Messenger\Asynchronous\Middleware](symfony/component/messenger/asynchronous/middleware) * [Symfony\Component\Messenger\Asynchronous\Routing](symfony/component/messenger/asynchronous/routing) * [Symfony\Component\Messenger\Asynchronous\Transport](symfony/component/messenger/asynchronous/transport) * [Symfony\Component\Messenger\Command](symfony/component/messenger/command) * [Symfony\Component\Messenger\DataCollector](symfony/component/messenger/datacollector) * [Symfony\Component\Messenger\DependencyInjection](symfony/component/messenger/dependencyinjection) * [Symfony\Component\Messenger\Exception](symfony/component/messenger/exception) * [Symfony\Component\Messenger\Handler](symfony/component/messenger/handler) * [Symfony\Component\Messenger\Handler\Locator](symfony/component/messenger/handler/locator) * [Symfony\Component\Messenger\Middleware](symfony/component/messenger/middleware) * [Symfony\Component\Messenger\Middleware\Configuration](symfony/component/messenger/middleware/configuration) * [Symfony\Component\Messenger\Transport](symfony/component/messenger/transport) * [Symfony\Component\Messenger\Transport\AmqpExt](symfony/component/messenger/transport/amqpext) * [Symfony\Component\Messenger\Transport\AmqpExt\Exception](symfony/component/messenger/transport/amqpext/exception) * [Symfony\Component\Messenger\Transport\Enhancers](symfony/component/messenger/transport/enhancers) * [Symfony\Component\Messenger\Transport\Serialization](symfony/component/messenger/transport/serialization) * [Symfony\Component\OptionsResolver](symfony/component/optionsresolver) * [Symfony\Component\OptionsResolver\Debug](symfony/component/optionsresolver/debug) * [Symfony\Component\OptionsResolver\Exception](symfony/component/optionsresolver/exception) * [Symfony\Component\Process](symfony/component/process) * [Symfony\Component\Process\Exception](symfony/component/process/exception) * [Symfony\Component\Process\Pipes](symfony/component/process/pipes) * [Symfony\Component\PropertyAccess](symfony/component/propertyaccess) * [Symfony\Component\PropertyAccess\Exception](symfony/component/propertyaccess/exception) * [Symfony\Component\PropertyInfo](symfony/component/propertyinfo) * [Symfony\Component\PropertyInfo\DependencyInjection](symfony/component/propertyinfo/dependencyinjection) * [Symfony\Component\PropertyInfo\Extractor](symfony/component/propertyinfo/extractor) * [Symfony\Component\PropertyInfo\Util](symfony/component/propertyinfo/util) * [Symfony\Component\Routing](symfony/component/routing) * [Symfony\Component\Routing\Annotation](symfony/component/routing/annotation) * [Symfony\Component\Routing\DependencyInjection](symfony/component/routing/dependencyinjection) * [Symfony\Component\Routing\Exception](symfony/component/routing/exception) * [Symfony\Component\Routing\Generator](symfony/component/routing/generator) * [Symfony\Component\Routing\Generator\Dumper](symfony/component/routing/generator/dumper) * [Symfony\Component\Routing\Loader](symfony/component/routing/loader) * [Symfony\Component\Routing\Loader\Configurator](symfony/component/routing/loader/configurator) * [Symfony\Component\Routing\Loader\Configurator\Traits](symfony/component/routing/loader/configurator/traits) * [Symfony\Component\Routing\Loader\DependencyInjection](symfony/component/routing/loader/dependencyinjection) * [Symfony\Component\Routing\Matcher](symfony/component/routing/matcher) * [Symfony\Component\Routing\Matcher\Dumper](symfony/component/routing/matcher/dumper) * [Symfony\Component\Security](symfony/component/security) * [Symfony\Component\Security\Core](symfony/component/security/core) * [Symfony\Component\Security\Core\Authentication](symfony/component/security/core/authentication) * [Symfony\Component\Security\Core\Authentication\Provider](symfony/component/security/core/authentication/provider) * [Symfony\Component\Security\Core\Authentication\RememberMe](symfony/component/security/core/authentication/rememberme) * [Symfony\Component\Security\Core\Authentication\Token](symfony/component/security/core/authentication/token) * [Symfony\Component\Security\Core\Authentication\Token\Storage](symfony/component/security/core/authentication/token/storage) * [Symfony\Component\Security\Core\Authorization](symfony/component/security/core/authorization) * [Symfony\Component\Security\Core\Authorization\Voter](symfony/component/security/core/authorization/voter) * [Symfony\Component\Security\Core\Encoder](symfony/component/security/core/encoder) * [Symfony\Component\Security\Core\Event](symfony/component/security/core/event) * [Symfony\Component\Security\Core\Exception](symfony/component/security/core/exception) * [Symfony\Component\Security\Core\Role](symfony/component/security/core/role) * [Symfony\Component\Security\Core\User](symfony/component/security/core/user) * [Symfony\Component\Security\Core\Validator](symfony/component/security/core/validator) * [Symfony\Component\Security\Core\Validator\Constraints](symfony/component/security/core/validator/constraints) * [Symfony\Component\Security\Csrf](symfony/component/security/csrf) * [Symfony\Component\Security\Csrf\Exception](symfony/component/security/csrf/exception) * [Symfony\Component\Security\Csrf\TokenGenerator](symfony/component/security/csrf/tokengenerator) * [Symfony\Component\Security\Csrf\TokenStorage](symfony/component/security/csrf/tokenstorage) * [Symfony\Component\Security\Guard](symfony/component/security/guard) * [Symfony\Component\Security\Guard\Authenticator](symfony/component/security/guard/authenticator) * [Symfony\Component\Security\Guard\Firewall](symfony/component/security/guard/firewall) * [Symfony\Component\Security\Guard\Provider](symfony/component/security/guard/provider) * [Symfony\Component\Security\Guard\Token](symfony/component/security/guard/token) * [Symfony\Component\Security\Http](symfony/component/security/http) * [Symfony\Component\Security\Http\Authentication](symfony/component/security/http/authentication) * [Symfony\Component\Security\Http\Authorization](symfony/component/security/http/authorization) * [Symfony\Component\Security\Http\Controller](symfony/component/security/http/controller) * [Symfony\Component\Security\Http\EntryPoint](symfony/component/security/http/entrypoint) * [Symfony\Component\Security\Http\Event](symfony/component/security/http/event) * [Symfony\Component\Security\Http\Firewall](symfony/component/security/http/firewall) * [Symfony\Component\Security\Http\Logout](symfony/component/security/http/logout) * [Symfony\Component\Security\Http\RememberMe](symfony/component/security/http/rememberme) * [Symfony\Component\Security\Http\Session](symfony/component/security/http/session) * [Symfony\Component\Security\Http\Util](symfony/component/security/http/util) * [Symfony\Component\Serializer](symfony/component/serializer) * [Symfony\Component\Serializer\Annotation](symfony/component/serializer/annotation) * [Symfony\Component\Serializer\DependencyInjection](symfony/component/serializer/dependencyinjection) * [Symfony\Component\Serializer\Encoder](symfony/component/serializer/encoder) * [Symfony\Component\Serializer\Exception](symfony/component/serializer/exception) * [Symfony\Component\Serializer\Mapping](symfony/component/serializer/mapping) * [Symfony\Component\Serializer\Mapping\Factory](symfony/component/serializer/mapping/factory) * [Symfony\Component\Serializer\Mapping\Loader](symfony/component/serializer/mapping/loader) * [Symfony\Component\Serializer\NameConverter](symfony/component/serializer/nameconverter) * [Symfony\Component\Serializer\Normalizer](symfony/component/serializer/normalizer) * [Symfony\Component\Stopwatch](symfony/component/stopwatch) * [Symfony\Component\Templating](symfony/component/templating) * [Symfony\Component\Templating\Helper](symfony/component/templating/helper) * [Symfony\Component\Templating\Loader](symfony/component/templating/loader) * [Symfony\Component\Templating\Storage](symfony/component/templating/storage) * [Symfony\Component\Translation](symfony/component/translation) * [Symfony\Component\Translation\Catalogue](symfony/component/translation/catalogue) * [Symfony\Component\Translation\Command](symfony/component/translation/command) * [Symfony\Component\Translation\DataCollector](symfony/component/translation/datacollector) * [Symfony\Component\Translation\DependencyInjection](symfony/component/translation/dependencyinjection) * [Symfony\Component\Translation\Dumper](symfony/component/translation/dumper) * [Symfony\Component\Translation\Exception](symfony/component/translation/exception) * [Symfony\Component\Translation\Extractor](symfony/component/translation/extractor) * [Symfony\Component\Translation\Formatter](symfony/component/translation/formatter) * [Symfony\Component\Translation\Loader](symfony/component/translation/loader) * [Symfony\Component\Translation\Reader](symfony/component/translation/reader) * [Symfony\Component\Translation\Util](symfony/component/translation/util) * [Symfony\Component\Translation\Writer](symfony/component/translation/writer) * [Symfony\Component\Validator](symfony/component/validator) * [Symfony\Component\Validator\Constraints](symfony/component/validator/constraints) * [Symfony\Component\Validator\Context](symfony/component/validator/context) * [Symfony\Component\Validator\DataCollector](symfony/component/validator/datacollector) * [Symfony\Component\Validator\DependencyInjection](symfony/component/validator/dependencyinjection) * [Symfony\Component\Validator\Exception](symfony/component/validator/exception) * [Symfony\Component\Validator\Mapping](symfony/component/validator/mapping) * [Symfony\Component\Validator\Mapping\Cache](symfony/component/validator/mapping/cache) * [Symfony\Component\Validator\Mapping\Factory](symfony/component/validator/mapping/factory) * [Symfony\Component\Validator\Mapping\Loader](symfony/component/validator/mapping/loader) * [Symfony\Component\Validator\Test](symfony/component/validator/test) * [Symfony\Component\Validator\Util](symfony/component/validator/util) * [Symfony\Component\Validator\Validator](symfony/component/validator/validator) * [Symfony\Component\Validator\Violation](symfony/component/validator/violation) * [Symfony\Component\VarDumper](symfony/component/vardumper) * [Symfony\Component\VarDumper\Caster](symfony/component/vardumper/caster) * [Symfony\Component\VarDumper\Cloner](symfony/component/vardumper/cloner) * [Symfony\Component\VarDumper\Command](symfony/component/vardumper/command) * [Symfony\Component\VarDumper\Command\Descriptor](symfony/component/vardumper/command/descriptor) * [Symfony\Component\VarDumper\Dumper](symfony/component/vardumper/dumper) * [Symfony\Component\VarDumper\Dumper\ContextProvider](symfony/component/vardumper/dumper/contextprovider) * [Symfony\Component\VarDumper\Exception](symfony/component/vardumper/exception) * [Symfony\Component\VarDumper\Server](symfony/component/vardumper/server) * [Symfony\Component\VarDumper\Test](symfony/component/vardumper/test) * [Symfony\Component\WebLink](symfony/component/weblink) * [Symfony\Component\WebLink\EventListener](symfony/component/weblink/eventlistener) * [Symfony\Component\Workflow](symfony/component/workflow) * [Symfony\Component\Workflow\DependencyInjection](symfony/component/workflow/dependencyinjection) * [Symfony\Component\Workflow\Dumper](symfony/component/workflow/dumper) * [Symfony\Component\Workflow\Event](symfony/component/workflow/event) * [Symfony\Component\Workflow\EventListener](symfony/component/workflow/eventlistener) * [Symfony\Component\Workflow\Exception](symfony/component/workflow/exception) * [Symfony\Component\Workflow\MarkingStore](symfony/component/workflow/markingstore) * [Symfony\Component\Workflow\Metadata](symfony/component/workflow/metadata) * [Symfony\Component\Workflow\SupportStrategy](symfony/component/workflow/supportstrategy) * [Symfony\Component\Workflow\Validator](symfony/component/workflow/validator) * [Symfony\Component\Yaml](symfony/component/yaml) * [Symfony\Component\Yaml\Command](symfony/component/yaml/command) * [Symfony\Component\Yaml\Exception](symfony/component/yaml/exception) * [Symfony\Component\Yaml\Tag](symfony/component/yaml/tag)
programming_docs
symfony Symfony\Component Symfony\Component ================= Namespaces ---------- [Symfony\Component\Asset](component/asset)[Symfony\Component\BrowserKit](component/browserkit)[Symfony\Component\Cache](component/cache)[Symfony\Component\Config](component/config)[Symfony\Component\Console](component/console)[Symfony\Component\CssSelector](component/cssselector)[Symfony\Component\Debug](component/debug)[Symfony\Component\DependencyInjection](component/dependencyinjection)[Symfony\Component\DomCrawler](component/domcrawler)[Symfony\Component\Dotenv](component/dotenv)[Symfony\Component\EventDispatcher](component/eventdispatcher)[Symfony\Component\ExpressionLanguage](component/expressionlanguage)[Symfony\Component\Filesystem](component/filesystem)[Symfony\Component\Finder](component/finder)[Symfony\Component\Form](component/form)[Symfony\Component\HttpFoundation](component/httpfoundation)[Symfony\Component\HttpKernel](component/httpkernel)[Symfony\Component\Inflector](component/inflector)[Symfony\Component\Intl](component/intl)[Symfony\Component\Ldap](component/ldap)[Symfony\Component\Lock](component/lock)[Symfony\Component\Messenger](component/messenger)[Symfony\Component\OptionsResolver](component/optionsresolver)[Symfony\Component\Process](component/process)[Symfony\Component\PropertyAccess](component/propertyaccess)[Symfony\Component\PropertyInfo](component/propertyinfo)[Symfony\Component\Routing](component/routing)[Symfony\Component\Security](component/security)[Symfony\Component\Serializer](component/serializer)[Symfony\Component\Stopwatch](component/stopwatch)[Symfony\Component\Templating](component/templating)[Symfony\Component\Translation](component/translation)[Symfony\Component\Validator](component/validator)[Symfony\Component\VarDumper](component/vardumper)[Symfony\Component\WebLink](component/weblink)[Symfony\Component\Workflow](component/workflow)[Symfony\Component\Yaml](component/yaml) symfony Symfony\Bundle Symfony\Bundle ============== Namespaces ---------- [Symfony\Bundle\DebugBundle](bundle/debugbundle)[Symfony\Bundle\FrameworkBundle](bundle/frameworkbundle)[Symfony\Bundle\SecurityBundle](bundle/securitybundle)[Symfony\Bundle\TwigBundle](bundle/twigbundle)[Symfony\Bundle\WebProfilerBundle](bundle/webprofilerbundle)[Symfony\Bundle\WebServerBundle](bundle/webserverbundle) Classes ------- | | | | --- | --- | | [FullStack](bundle/fullstack "Symfony\Bundle\FullStack") | A marker to be able to check if symfony/symfony is installed instead of the individual components/bundles. | symfony Symfony\Bridge Symfony\Bridge ============== Namespaces ---------- [Symfony\Bridge\Doctrine](bridge/doctrine)[Symfony\Bridge\Monolog](bridge/monolog)[Symfony\Bridge\PhpUnit](bridge/phpunit)[Symfony\Bridge\ProxyManager](bridge/proxymanager)[Symfony\Bridge\Twig](bridge/twig) symfony Symfony\Bridge\PhpUnit Symfony\Bridge\PhpUnit ====================== Namespaces ---------- [Symfony\Bridge\PhpUnit\Legacy](phpunit/legacy)[Symfony\Bridge\PhpUnit\TextUI](phpunit/textui) Classes ------- | | | | --- | --- | | [ClockMock](phpunit/clockmock "Symfony\Bridge\PhpUnit\ClockMock") | | | [CoverageListener](phpunit/coveragelistener "Symfony\Bridge\PhpUnit\CoverageListener") | | | [DeprecationErrorHandler](phpunit/deprecationerrorhandler "Symfony\Bridge\PhpUnit\DeprecationErrorHandler") | Catch deprecation notices and print a summary report at the end of the test suite. | | [DnsMock](phpunit/dnsmock "Symfony\Bridge\PhpUnit\DnsMock") | | | [SymfonyTestsListener](phpunit/symfonytestslistener "Symfony\Bridge\PhpUnit\SymfonyTestsListener") | | symfony Symfony\Bridge\ProxyManager Symfony\Bridge\ProxyManager =========================== Namespaces ---------- [Symfony\Bridge\ProxyManager\LazyProxy](proxymanager/lazyproxy) symfony Symfony\Bridge\Monolog Symfony\Bridge\Monolog ====================== Namespaces ---------- [Symfony\Bridge\Monolog\Formatter](monolog/formatter)[Symfony\Bridge\Monolog\Handler](monolog/handler)[Symfony\Bridge\Monolog\Processor](monolog/processor) Classes ------- | | | | --- | --- | | [Logger](monolog/logger "Symfony\Bridge\Monolog\Logger") | Logger. | symfony Symfony\Bridge\Doctrine Symfony\Bridge\Doctrine ======================= Namespaces ---------- [Symfony\Bridge\Doctrine\CacheWarmer](doctrine/cachewarmer)[Symfony\Bridge\Doctrine\DataCollector](doctrine/datacollector)[Symfony\Bridge\Doctrine\DataFixtures](doctrine/datafixtures)[Symfony\Bridge\Doctrine\DependencyInjection](doctrine/dependencyinjection)[Symfony\Bridge\Doctrine\Form](doctrine/form)[Symfony\Bridge\Doctrine\Logger](doctrine/logger)[Symfony\Bridge\Doctrine\Messenger](doctrine/messenger)[Symfony\Bridge\Doctrine\PropertyInfo](doctrine/propertyinfo)[Symfony\Bridge\Doctrine\Security](doctrine/security)[Symfony\Bridge\Doctrine\Test](doctrine/test)[Symfony\Bridge\Doctrine\Validator](doctrine/validator) Classes ------- | | | | --- | --- | | [ContainerAwareEventManager](doctrine/containerawareeventmanager "Symfony\Bridge\Doctrine\ContainerAwareEventManager") | Allows lazy loading of listener services. | | [ManagerRegistry](doctrine/managerregistry "Symfony\Bridge\Doctrine\ManagerRegistry") | References Doctrine connections and entity/document managers. | Interfaces ---------- | | | | --- | --- | | *[RegistryInterface](doctrine/registryinterface "Symfony\Bridge\Doctrine\RegistryInterface")* | References Doctrine connections and entity managers. | symfony Symfony\Bridge\Twig Symfony\Bridge\Twig =================== Namespaces ---------- [Symfony\Bridge\Twig\Command](twig/command)[Symfony\Bridge\Twig\DataCollector](twig/datacollector)[Symfony\Bridge\Twig\Extension](twig/extension)[Symfony\Bridge\Twig\Form](twig/form)[Symfony\Bridge\Twig\Node](twig/node)[Symfony\Bridge\Twig\NodeVisitor](twig/nodevisitor)[Symfony\Bridge\Twig\TokenParser](twig/tokenparser)[Symfony\Bridge\Twig\Translation](twig/translation) Classes ------- | | | | --- | --- | | [AppVariable](twig/appvariable "Symfony\Bridge\Twig\AppVariable") | Exposes some Symfony parameters and services as an "app" global variable. | | [TwigEngine](twig/twigengine "Symfony\Bridge\Twig\TwigEngine") | This engine knows how to render Twig templates. | | [UndefinedCallableHandler](twig/undefinedcallablehandler "Symfony\Bridge\Twig\UndefinedCallableHandler") | | symfony Symfony\Bridge\Doctrine\Form Symfony\Bridge\Doctrine\Form ============================ Namespaces ---------- [Symfony\Bridge\Doctrine\Form\ChoiceList](form/choicelist)[Symfony\Bridge\Doctrine\Form\DataTransformer](form/datatransformer)[Symfony\Bridge\Doctrine\Form\EventListener](form/eventlistener)[Symfony\Bridge\Doctrine\Form\Type](form/type) Classes ------- | | | | --- | --- | | [DoctrineOrmExtension](form/doctrineormextension "Symfony\Bridge\Doctrine\Form\DoctrineOrmExtension") | | | [DoctrineOrmTypeGuesser](form/doctrineormtypeguesser "Symfony\Bridge\Doctrine\Form\DoctrineOrmTypeGuesser") | | symfony Symfony\Bridge\Doctrine\DataFixtures Symfony\Bridge\Doctrine\DataFixtures ==================================== Classes ------- | | | | --- | --- | | [ContainerAwareLoader](datafixtures/containerawareloader "Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader") | Doctrine data fixtures loader that injects the service container into fixture objects that implement ContainerAwareInterface. | symfony Symfony\Bridge\Doctrine\DataCollector Symfony\Bridge\Doctrine\DataCollector ===================================== Classes ------- | | | | --- | --- | | [DoctrineDataCollector](datacollector/doctrinedatacollector "Symfony\Bridge\Doctrine\DataCollector\DoctrineDataCollector") | DoctrineDataCollector. | symfony Symfony\Bridge\Doctrine\Logger Symfony\Bridge\Doctrine\Logger ============================== Classes ------- | | | | --- | --- | | [DbalLogger](logger/dballogger "Symfony\Bridge\Doctrine\Logger\DbalLogger") | | symfony Symfony\Bridge\Doctrine\Validator Symfony\Bridge\Doctrine\Validator ================================= Namespaces ---------- [Symfony\Bridge\Doctrine\Validator\Constraints](validator/constraints) Classes ------- | | | | --- | --- | | [DoctrineInitializer](validator/doctrineinitializer "Symfony\Bridge\Doctrine\Validator\DoctrineInitializer") | Automatically loads proxy object before validation. | symfony Symfony\Bridge\Doctrine\PropertyInfo Symfony\Bridge\Doctrine\PropertyInfo ==================================== Classes ------- | | | | --- | --- | | [DoctrineExtractor](propertyinfo/doctrineextractor "Symfony\Bridge\Doctrine\PropertyInfo\DoctrineExtractor") | Extracts data using Doctrine ORM and ODM metadata. | symfony Symfony\Bridge\Doctrine\Messenger Symfony\Bridge\Doctrine\Messenger ================================= Classes ------- | | | | --- | --- | | [DoctrineTransactionMiddleware](messenger/doctrinetransactionmiddleware "Symfony\Bridge\Doctrine\Messenger\DoctrineTransactionMiddleware") | Wraps all handlers in a single doctrine transaction. | | [DoctrineTransactionMiddlewareFactory](messenger/doctrinetransactionmiddlewarefactory "Symfony\Bridge\Doctrine\Messenger\DoctrineTransactionMiddlewareFactory") | Create a Doctrine ORM transaction middleware to be used in a message bus from an entity manager name. | symfony Symfony\Bridge\Doctrine\Test Symfony\Bridge\Doctrine\Test ============================ Classes ------- | | | | --- | --- | | [DoctrineTestHelper](test/doctrinetesthelper "Symfony\Bridge\Doctrine\Test\DoctrineTestHelper") | Provides utility functions needed in tests. | | [TestRepositoryFactory](test/testrepositoryfactory "Symfony\Bridge\Doctrine\Test\TestRepositoryFactory") | | symfony ContainerAwareEventManager ContainerAwareEventManager =========================== class **ContainerAwareEventManager** extends EventManager Allows lazy loading of listener services. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(ContainerInterface $container) | | | bool | [dispatchEvent](#method_dispatchEvent)(string $eventName, EventArgs $eventArgs = null) Dispatches an event to all registered listeners. | | | array | [getListeners](#method_getListeners)(string $event = null) Gets the listeners of a specific event or all listeners. | | | bool | [hasListeners](#method_hasListeners)(string $event) Checks whether an event has any registered listeners. | | | | [addEventListener](#method_addEventListener)(string|array $events, object|string $listener) Adds an event listener that listens on the specified events. | | | | [removeEventListener](#method_removeEventListener)(string|array $events, object|string $listener) Removes an event listener from the specified events. | | Details ------- ### \_\_construct(ContainerInterface $container) #### Parameters | | | | | --- | --- | --- | | ContainerInterface | $container | | ### bool dispatchEvent(string $eventName, EventArgs $eventArgs = null) Dispatches an event to all registered listeners. #### Parameters | | | | | --- | --- | --- | | string | $eventName | The name of the event to dispatch. The name of the event is the name of the method that is invoked on listeners. | | EventArgs | $eventArgs | The event arguments to pass to the event handlers/listeners. If not supplied, the single empty EventArgs instance is used. | #### Return Value | | | | --- | --- | | bool | | ### array getListeners(string $event = null) Gets the listeners of a specific event or all listeners. #### Parameters | | | | | --- | --- | --- | | string | $event | The name of the event | #### Return Value | | | | --- | --- | | array | The event listeners for the specified event, or all event listeners | ### bool hasListeners(string $event) Checks whether an event has any registered listeners. #### Parameters | | | | | --- | --- | --- | | string | $event | | #### Return Value | | | | --- | --- | | bool | TRUE if the specified event has any listeners, FALSE otherwise | ### addEventListener(string|array $events, object|string $listener) Adds an event listener that listens on the specified events. #### Parameters | | | | | --- | --- | --- | | string|array | $events | The event(s) to listen on | | object|string | $listener | The listener object | #### Exceptions | | | | --- | --- | | [RuntimeException](http://php.net/RuntimeException) | | ### removeEventListener(string|array $events, object|string $listener) Removes an event listener from the specified events. #### Parameters | | | | | --- | --- | --- | | string|array | $events | | | object|string | $listener | | symfony ManagerRegistry ManagerRegistry ================ abstract class **ManagerRegistry** extends AbstractManagerRegistry References Doctrine connections and entity/document managers. Properties ---------- | | | | | | --- | --- | --- | --- | | protected [Container](../../component/dependencyinjection/container "Symfony\Component\DependencyInjection\Container") | $container | | | Methods ------- | | | | | --- | --- | --- | | | [getService](#method_getService)($name) {@inheritdoc} | | | | [resetService](#method_resetService)($name) {@inheritdoc} | | Details ------- ### protected getService($name) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | | $name | | ### protected resetService($name) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | | $name | | symfony Symfony\Bridge\Doctrine\Security Symfony\Bridge\Doctrine\Security ================================ Namespaces ---------- [Symfony\Bridge\Doctrine\Security\RememberMe](security/rememberme)[Symfony\Bridge\Doctrine\Security\User](security/user) symfony Symfony\Bridge\Doctrine\DependencyInjection Symfony\Bridge\Doctrine\DependencyInjection =========================================== Namespaces ---------- [Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass](dependencyinjection/compilerpass)[Symfony\Bridge\Doctrine\DependencyInjection\Security](dependencyinjection/security) Classes ------- | | | | --- | --- | | [AbstractDoctrineExtension](dependencyinjection/abstractdoctrineextension "Symfony\Bridge\Doctrine\DependencyInjection\AbstractDoctrineExtension") | This abstract classes groups common code that Doctrine Object Manager extensions (ORM, MongoDB, CouchDB) need. | symfony RegistryInterface RegistryInterface ================== interface **RegistryInterface** implements ManagerRegistry References Doctrine connections and entity managers. Methods ------- | | | | | --- | --- | --- | | string | [getDefaultEntityManagerName](#method_getDefaultEntityManagerName)() Gets the default entity manager name. | | | EntityManager | [getEntityManager](#method_getEntityManager)(string $name = null) Gets a named entity manager. | | | array | [getEntityManagers](#method_getEntityManagers)() Gets an array of all registered entity managers. | | | EntityManager | [resetEntityManager](#method_resetEntityManager)(string $name = null) Resets a named entity manager. | | | string | [getEntityNamespace](#method_getEntityNamespace)(string $alias) Resolves a registered namespace alias to the full namespace. | | | array | [getEntityManagerNames](#method_getEntityManagerNames)() Gets all connection names. | | | EntityManager|null | [getEntityManagerForClass](#method_getEntityManagerForClass)(string $class) Gets the entity manager associated with a given class. | | Details ------- ### string getDefaultEntityManagerName() Gets the default entity manager name. #### Return Value | | | | --- | --- | | string | The default entity manager name | ### EntityManager getEntityManager(string $name = null) Gets a named entity manager. #### Parameters | | | | | --- | --- | --- | | string | $name | The entity manager name (null for the default one) | #### Return Value | | | | --- | --- | | EntityManager | | ### array getEntityManagers() Gets an array of all registered entity managers. #### Return Value | | | | --- | --- | | array | An array of EntityManager instances | ### EntityManager resetEntityManager(string $name = null) Resets a named entity manager. This method is useful when an entity manager has been closed because of a rollbacked transaction AND when you think that it makes sense to get a new one to replace the closed one. Be warned that you will get a brand new entity manager as the existing one is not useable anymore. This means that any other object with a dependency on this entity manager will hold an obsolete reference. You can inject the registry instead to avoid this problem. #### Parameters | | | | | --- | --- | --- | | string | $name | The entity manager name (null for the default one) | #### Return Value | | | | --- | --- | | EntityManager | | ### string getEntityNamespace(string $alias) Resolves a registered namespace alias to the full namespace. This method looks for the alias in all registered entity managers. #### Parameters | | | | | --- | --- | --- | | string | $alias | The alias | #### Return Value | | | | --- | --- | | string | The full namespace | #### See also | | | | --- | --- | | Configuration::getEntityNamespace | | ### array getEntityManagerNames() Gets all connection names. #### Return Value | | | | --- | --- | | array | An array of connection names | ### EntityManager|null getEntityManagerForClass(string $class) Gets the entity manager associated with a given class. #### Parameters | | | | | --- | --- | --- | | string | $class | A Doctrine Entity class name | #### Return Value | | | | --- | --- | | EntityManager|null | | symfony Symfony\Bridge\Doctrine\CacheWarmer Symfony\Bridge\Doctrine\CacheWarmer =================================== Classes ------- | | | | --- | --- | | [ProxyCacheWarmer](cachewarmer/proxycachewarmer "Symfony\Bridge\Doctrine\CacheWarmer\ProxyCacheWarmer") | The proxy generator cache warmer generates all entity proxies. | symfony DoctrineDataCollector DoctrineDataCollector ====================== class **DoctrineDataCollector** extends [DataCollector](../../../component/httpkernel/datacollector/datacollector "Symfony\Component\HttpKernel\DataCollector\DataCollector") DoctrineDataCollector. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $data | | from [DataCollector](../../../component/httpkernel/datacollector/datacollector#property_data "Symfony\Component\HttpKernel\DataCollector\DataCollector") | Methods ------- | | | | | --- | --- | --- | | | [serialize](#method_serialize)() | from [DataCollector](../../../component/httpkernel/datacollector/datacollector#method_serialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [unserialize](#method_unserialize)($data) | from [DataCollector](../../../component/httpkernel/datacollector/datacollector#method_unserialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | [Data](../../../component/vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | [cloneVar](#method_cloneVar)(mixed $var) Converts the variable into a serializable Data instance. | from [DataCollector](../../../component/httpkernel/datacollector/datacollector#method_cloneVar "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | callable[] | [getCasters](#method_getCasters)() | from [DataCollector](../../../component/httpkernel/datacollector/datacollector#method_getCasters "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [\_\_construct](#method___construct)(ManagerRegistry $registry) | | | | [addLogger](#method_addLogger)(string $name, DebugStack $logger) Adds the stack logger for a connection. | | | | [collect](#method_collect)([Request](../../../component/httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../../component/httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. | | | | [reset](#method_reset)() Resets this data collector to its initial state. | | | | [getManagers](#method_getManagers)() | | | | [getConnections](#method_getConnections)() | | | | [getQueryCount](#method_getQueryCount)() | | | | [getQueries](#method_getQueries)() | | | | [getTime](#method_getTime)() | | | string | [getName](#method_getName)() Returns the name of the collector. | | Details ------- ### serialize() ### unserialize($data) #### Parameters | | | | | --- | --- | --- | | | $data | | ### protected [Data](../../../component/vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") cloneVar(mixed $var) Converts the variable into a serializable Data instance. This array can be displayed in the template using the VarDumper component. #### Parameters | | | | | --- | --- | --- | | mixed | $var | | #### Return Value | | | | --- | --- | | [Data](../../../component/vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | | ### protected callable[] getCasters() #### Return Value | | | | --- | --- | | callable[] | The casters to add to the cloner | ### \_\_construct(ManagerRegistry $registry) #### Parameters | | | | | --- | --- | --- | | ManagerRegistry | $registry | | ### addLogger(string $name, DebugStack $logger) Adds the stack logger for a connection. #### Parameters | | | | | --- | --- | --- | | string | $name | | | DebugStack | $logger | | ### collect([Request](../../../component/httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../../component/httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. #### Parameters | | | | | --- | --- | --- | | [Request](../../../component/httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../../component/httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | | [Exception](http://php.net/Exception) | $exception | | ### reset() Resets this data collector to its initial state. ### getManagers() ### getConnections() ### getQueryCount() ### getQueries() ### getTime() ### string getName() Returns the name of the collector. #### Return Value | | | | --- | --- | | string | The collector name |
programming_docs
symfony Symfony\Bridge\Doctrine\Form\Type Symfony\Bridge\Doctrine\Form\Type ================================= Classes ------- | | | | --- | --- | | [DoctrineType](type/doctrinetype "Symfony\Bridge\Doctrine\Form\Type\DoctrineType") | | | [EntityType](type/entitytype "Symfony\Bridge\Doctrine\Form\Type\EntityType") | | symfony Symfony\Bridge\Doctrine\Form\DataTransformer Symfony\Bridge\Doctrine\Form\DataTransformer ============================================ Classes ------- | | | | --- | --- | | [CollectionToArrayTransformer](datatransformer/collectiontoarraytransformer "Symfony\Bridge\Doctrine\Form\DataTransformer\CollectionToArrayTransformer") | | symfony Symfony\Bridge\Doctrine\Form\ChoiceList Symfony\Bridge\Doctrine\Form\ChoiceList ======================================= Classes ------- | | | | --- | --- | | [DoctrineChoiceLoader](choicelist/doctrinechoiceloader "Symfony\Bridge\Doctrine\Form\ChoiceList\DoctrineChoiceLoader") | Loads choices using a Doctrine object manager. | | [IdReader](choicelist/idreader "Symfony\Bridge\Doctrine\Form\ChoiceList\IdReader") | A utility for reading object IDs. | | [ORMQueryBuilderLoader](choicelist/ormquerybuilderloader "Symfony\Bridge\Doctrine\Form\ChoiceList\ORMQueryBuilderLoader") | Loads entities using a {@link QueryBuilder} instance. | Interfaces ---------- | | | | --- | --- | | *[EntityLoaderInterface](choicelist/entityloaderinterface "Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface")* | Custom loader for entities in the choice list. | symfony DoctrineOrmExtension DoctrineOrmExtension ===================== class **DoctrineOrmExtension** extends [AbstractExtension](../../../component/form/abstractextension "Symfony\Component\Form\AbstractExtension") Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $registry | | | Methods ------- | | | | | --- | --- | --- | | [FormTypeInterface](../../../component/form/formtypeinterface "Symfony\Component\Form\FormTypeInterface") | [getType](#method_getType)(string $name) Returns a type by name. | from [AbstractExtension](../../../component/form/abstractextension#method_getType "Symfony\Component\Form\AbstractExtension") | | bool | [hasType](#method_hasType)(string $name) Returns whether the given type is supported. | from [AbstractExtension](../../../component/form/abstractextension#method_hasType "Symfony\Component\Form\AbstractExtension") | | [FormTypeExtensionInterface](../../../component/form/formtypeextensioninterface "Symfony\Component\Form\FormTypeExtensionInterface")[] | [getTypeExtensions](#method_getTypeExtensions)(string $name) Returns the extensions for the given type. | from [AbstractExtension](../../../component/form/abstractextension#method_getTypeExtensions "Symfony\Component\Form\AbstractExtension") | | bool | [hasTypeExtensions](#method_hasTypeExtensions)(string $name) Returns whether this extension provides type extensions for the given type. | from [AbstractExtension](../../../component/form/abstractextension#method_hasTypeExtensions "Symfony\Component\Form\AbstractExtension") | | [FormTypeGuesserInterface](../../../component/form/formtypeguesserinterface "Symfony\Component\Form\FormTypeGuesserInterface")|null | [getTypeGuesser](#method_getTypeGuesser)() Returns the type guesser provided by this extension. | from [AbstractExtension](../../../component/form/abstractextension#method_getTypeGuesser "Symfony\Component\Form\AbstractExtension") | | [FormTypeInterface](../../../component/form/formtypeinterface "Symfony\Component\Form\FormTypeInterface")[] | [loadTypes](#method_loadTypes)() Registers the types. | | | [FormTypeExtensionInterface](../../../component/form/formtypeextensioninterface "Symfony\Component\Form\FormTypeExtensionInterface")[] | [loadTypeExtensions](#method_loadTypeExtensions)() Registers the type extensions. | from [AbstractExtension](../../../component/form/abstractextension#method_loadTypeExtensions "Symfony\Component\Form\AbstractExtension") | | [FormTypeGuesserInterface](../../../component/form/formtypeguesserinterface "Symfony\Component\Form\FormTypeGuesserInterface")|null | [loadTypeGuesser](#method_loadTypeGuesser)() Registers the type guesser. | | | | [\_\_construct](#method___construct)(ManagerRegistry $registry) | | Details ------- ### [FormTypeInterface](../../../component/form/formtypeinterface "Symfony\Component\Form\FormTypeInterface") getType(string $name) Returns a type by name. #### Parameters | | | | | --- | --- | --- | | string | $name | The name of the type | #### Return Value | | | | --- | --- | | [FormTypeInterface](../../../component/form/formtypeinterface "Symfony\Component\Form\FormTypeInterface") | The type | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](../../../component/form/exception/invalidargumentexception "Symfony\Component\Form\Exception\InvalidArgumentException") | if the given type is not supported by this extension | ### bool hasType(string $name) Returns whether the given type is supported. #### Parameters | | | | | --- | --- | --- | | string | $name | The name of the type | #### Return Value | | | | --- | --- | | bool | Whether the type is supported by this extension | ### [FormTypeExtensionInterface](../../../component/form/formtypeextensioninterface "Symfony\Component\Form\FormTypeExtensionInterface")[] getTypeExtensions(string $name) Returns the extensions for the given type. #### Parameters | | | | | --- | --- | --- | | string | $name | The name of the type | #### Return Value | | | | --- | --- | | [FormTypeExtensionInterface](../../../component/form/formtypeextensioninterface "Symfony\Component\Form\FormTypeExtensionInterface")[] | An array of extensions as FormTypeExtensionInterface instances | ### bool hasTypeExtensions(string $name) Returns whether this extension provides type extensions for the given type. #### Parameters | | | | | --- | --- | --- | | string | $name | The name of the type | #### Return Value | | | | --- | --- | | bool | Whether the given type has extensions | ### [FormTypeGuesserInterface](../../../component/form/formtypeguesserinterface "Symfony\Component\Form\FormTypeGuesserInterface")|null getTypeGuesser() Returns the type guesser provided by this extension. #### Return Value | | | | --- | --- | | [FormTypeGuesserInterface](../../../component/form/formtypeguesserinterface "Symfony\Component\Form\FormTypeGuesserInterface")|null | The type guesser | ### protected [FormTypeInterface](../../../component/form/formtypeinterface "Symfony\Component\Form\FormTypeInterface")[] loadTypes() Registers the types. #### Return Value | | | | --- | --- | | [FormTypeInterface](../../../component/form/formtypeinterface "Symfony\Component\Form\FormTypeInterface")[] | An array of FormTypeInterface instances | ### protected [FormTypeExtensionInterface](../../../component/form/formtypeextensioninterface "Symfony\Component\Form\FormTypeExtensionInterface")[] loadTypeExtensions() Registers the type extensions. #### Return Value | | | | --- | --- | | [FormTypeExtensionInterface](../../../component/form/formtypeextensioninterface "Symfony\Component\Form\FormTypeExtensionInterface")[] | An array of FormTypeExtensionInterface instances | ### protected [FormTypeGuesserInterface](../../../component/form/formtypeguesserinterface "Symfony\Component\Form\FormTypeGuesserInterface")|null loadTypeGuesser() Registers the type guesser. #### Return Value | | | | --- | --- | | [FormTypeGuesserInterface](../../../component/form/formtypeguesserinterface "Symfony\Component\Form\FormTypeGuesserInterface")|null | A type guesser | ### \_\_construct(ManagerRegistry $registry) #### Parameters | | | | | --- | --- | --- | | ManagerRegistry | $registry | | symfony DoctrineOrmTypeGuesser DoctrineOrmTypeGuesser ======================= class **DoctrineOrmTypeGuesser** implements [FormTypeGuesserInterface](../../../component/form/formtypeguesserinterface "Symfony\Component\Form\FormTypeGuesserInterface") Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $registry | | | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(ManagerRegistry $registry) | | | [TypeGuess](../../../component/form/guess/typeguess "Symfony\Component\Form\Guess\TypeGuess")|null | [guessType](#method_guessType)(string $class, string $property) Returns a field guess for a property name of a class. | | | [ValueGuess](../../../component/form/guess/valueguess "Symfony\Component\Form\Guess\ValueGuess") | [guessRequired](#method_guessRequired)(string $class, string $property) Returns a guess whether a property of a class is required. | | | [ValueGuess](../../../component/form/guess/valueguess "Symfony\Component\Form\Guess\ValueGuess")|null | [guessMaxLength](#method_guessMaxLength)(string $class, string $property) Returns a guess about the field's maximum length. | | | [ValueGuess](../../../component/form/guess/valueguess "Symfony\Component\Form\Guess\ValueGuess")|null | [guessPattern](#method_guessPattern)(string $class, string $property) Returns a guess about the field's pattern. | | | | [getMetadata](#method_getMetadata)($class) | | Details ------- ### \_\_construct(ManagerRegistry $registry) #### Parameters | | | | | --- | --- | --- | | ManagerRegistry | $registry | | ### [TypeGuess](../../../component/form/guess/typeguess "Symfony\Component\Form\Guess\TypeGuess")|null guessType(string $class, string $property) Returns a field guess for a property name of a class. #### Parameters | | | | | --- | --- | --- | | string | $class | The fully qualified class name | | string | $property | The name of the property to guess for | #### Return Value | | | | --- | --- | | [TypeGuess](../../../component/form/guess/typeguess "Symfony\Component\Form\Guess\TypeGuess")|null | A guess for the field's type and options | ### [ValueGuess](../../../component/form/guess/valueguess "Symfony\Component\Form\Guess\ValueGuess") guessRequired(string $class, string $property) Returns a guess whether a property of a class is required. #### Parameters | | | | | --- | --- | --- | | string | $class | The fully qualified class name | | string | $property | The name of the property to guess for | #### Return Value | | | | --- | --- | | [ValueGuess](../../../component/form/guess/valueguess "Symfony\Component\Form\Guess\ValueGuess") | A guess for the field's required setting | ### [ValueGuess](../../../component/form/guess/valueguess "Symfony\Component\Form\Guess\ValueGuess")|null guessMaxLength(string $class, string $property) Returns a guess about the field's maximum length. #### Parameters | | | | | --- | --- | --- | | string | $class | The fully qualified class name | | string | $property | The name of the property to guess for | #### Return Value | | | | --- | --- | | [ValueGuess](../../../component/form/guess/valueguess "Symfony\Component\Form\Guess\ValueGuess")|null | A guess for the field's maximum length | ### [ValueGuess](../../../component/form/guess/valueguess "Symfony\Component\Form\Guess\ValueGuess")|null guessPattern(string $class, string $property) Returns a guess about the field's pattern. * When you have a min value, you guess a min length of this min (LOW\_CONFIDENCE) , lines below * If this value is a float type, this is wrong so you guess null with MEDIUM\_CONFIDENCE to override the previous guess. Example: You want a float greater than 5, 4.512313 is not valid but length(4.512314) > length(5) #### Parameters | | | | | --- | --- | --- | | string | $class | The fully qualified class name | | string | $property | The name of the property to guess for | #### Return Value | | | | --- | --- | | [ValueGuess](../../../component/form/guess/valueguess "Symfony\Component\Form\Guess\ValueGuess")|null | A guess for the field's required pattern | ### protected getMetadata($class) #### Parameters | | | | | --- | --- | --- | | | $class | | symfony Symfony\Bridge\Doctrine\Form\EventListener Symfony\Bridge\Doctrine\Form\EventListener ========================================== Classes ------- | | | | --- | --- | | [MergeDoctrineCollectionListener](eventlistener/mergedoctrinecollectionlistener "Symfony\Bridge\Doctrine\Form\EventListener\MergeDoctrineCollectionListener") | Merge changes from the request to a Doctrine\Common\Collections\Collection instance. | symfony ORMQueryBuilderLoader ORMQueryBuilderLoader ====================== class **ORMQueryBuilderLoader** implements [EntityLoaderInterface](entityloaderinterface "Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface") Loads entities using a {@link QueryBuilder} instance. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(QueryBuilder $queryBuilder) Construct an ORM Query Builder Loader. | | | array | [getEntities](#method_getEntities)() Returns an array of entities that are valid choices in the corresponding choice list. | | | array | [getEntitiesByIds](#method_getEntitiesByIds)(string $identifier, array $values) Returns an array of entities matching the given identifiers. | | Details ------- ### \_\_construct(QueryBuilder $queryBuilder) Construct an ORM Query Builder Loader. #### Parameters | | | | | --- | --- | --- | | QueryBuilder | $queryBuilder | The query builder for creating the query builder | ### array getEntities() Returns an array of entities that are valid choices in the corresponding choice list. #### Return Value | | | | --- | --- | | array | The entities | ### array getEntitiesByIds(string $identifier, array $values) Returns an array of entities matching the given identifiers. #### Parameters | | | | | --- | --- | --- | | string | $identifier | The identifier field of the object. This method is not applicable for fields with multiple identifiers. | | array | $values | The values of the identifiers | #### Return Value | | | | --- | --- | | array | The entities | symfony EntityLoaderInterface EntityLoaderInterface ====================== interface **EntityLoaderInterface** Custom loader for entities in the choice list. Methods ------- | | | | | --- | --- | --- | | array | [getEntities](#method_getEntities)() Returns an array of entities that are valid choices in the corresponding choice list. | | | array | [getEntitiesByIds](#method_getEntitiesByIds)(string $identifier, array $values) Returns an array of entities matching the given identifiers. | | Details ------- ### array getEntities() Returns an array of entities that are valid choices in the corresponding choice list. #### Return Value | | | | --- | --- | | array | The entities | ### array getEntitiesByIds(string $identifier, array $values) Returns an array of entities matching the given identifiers. #### Parameters | | | | | --- | --- | --- | | string | $identifier | The identifier field of the object. This method is not applicable for fields with multiple identifiers. | | array | $values | The values of the identifiers | #### Return Value | | | | --- | --- | | array | The entities | symfony DoctrineChoiceLoader DoctrineChoiceLoader ===================== class **DoctrineChoiceLoader** implements [ChoiceLoaderInterface](../../../../component/form/choicelist/loader/choiceloaderinterface "Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface") Loads choices using a Doctrine object manager. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(ObjectManager $manager, string $class, [IdReader](idreader "Symfony\Bridge\Doctrine\Form\ChoiceList\IdReader") $idReader = null, [EntityLoaderInterface](entityloaderinterface "Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface") $objectLoader = null) Creates a new choice loader. | | | [ChoiceListInterface](../../../../component/form/choicelist/choicelistinterface "Symfony\Component\Form\ChoiceList\ChoiceListInterface") | [loadChoiceList](#method_loadChoiceList)(callable|null $value = null) Loads a list of choices. | | | string[] | [loadValuesForChoices](#method_loadValuesForChoices)(array $choices, callable|null $value = null) Loads the values corresponding to the given choices. | | | array | [loadChoicesForValues](#method_loadChoicesForValues)(array $values, callable|null $value = null) Loads the choices corresponding to the given values. | | Details ------- ### \_\_construct(ObjectManager $manager, string $class, [IdReader](idreader "Symfony\Bridge\Doctrine\Form\ChoiceList\IdReader") $idReader = null, [EntityLoaderInterface](entityloaderinterface "Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface") $objectLoader = null) Creates a new choice loader. Optionally, an implementation of {@link EntityLoaderInterface} can be passed which optimizes the object loading for one of the Doctrine mapper implementations. #### Parameters | | | | | --- | --- | --- | | ObjectManager | $manager | The object manager | | string | $class | The class name of the loaded objects | | [IdReader](idreader "Symfony\Bridge\Doctrine\Form\ChoiceList\IdReader") | $idReader | The reader for the object IDs | | [EntityLoaderInterface](entityloaderinterface "Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface") | $objectLoader | The objects loader | ### [ChoiceListInterface](../../../../component/form/choicelist/choicelistinterface "Symfony\Component\Form\ChoiceList\ChoiceListInterface") loadChoiceList(callable|null $value = null) Loads a list of choices. Optionally, a callable can be passed for generating the choice values. The callable receives the choice as first and the array key as the second argument. #### Parameters | | | | | --- | --- | --- | | callable|null | $value | The callable which generates the values from choices | #### Return Value | | | | --- | --- | | [ChoiceListInterface](../../../../component/form/choicelist/choicelistinterface "Symfony\Component\Form\ChoiceList\ChoiceListInterface") | The loaded choice list | ### string[] loadValuesForChoices(array $choices, callable|null $value = null) Loads the values corresponding to the given choices. The values are returned with the same keys and in the same order as the corresponding choices in the given array. Optionally, a callable can be passed for generating the choice values. The callable receives the choice as first and the array key as the second argument. #### Parameters | | | | | --- | --- | --- | | array | $choices | An array of choices. Non-existing choices in this array are ignored | | callable|null | $value | The callable generating the choice values | #### Return Value | | | | --- | --- | | string[] | An array of choice values | ### array loadChoicesForValues(array $values, callable|null $value = null) Loads the choices corresponding to the given values. The choices are returned with the same keys and in the same order as the corresponding values in the given array. Optionally, a callable can be passed for generating the choice values. The callable receives the choice as first and the array key as the second argument. #### Parameters | | | | | --- | --- | --- | | array | $values | An array of choice values. Non-existing values in this array are ignored | | callable|null | $value | The callable generating the choice values | #### Return Value | | | | --- | --- | | array | An array of choices | symfony IdReader IdReader ========= class **IdReader** A utility for reading object IDs. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(ObjectManager $om, ClassMetadata $classMetadata) | | | bool | [isSingleId](#method_isSingleId)() Returns whether the class has a single-column ID. | | | bool | [isIntId](#method_isIntId)() Returns whether the class has a single-column integer ID. | | | mixed | [getIdValue](#method_getIdValue)(object $object) Returns the ID value for an object. | | | string | [getIdField](#method_getIdField)() Returns the name of the ID field. | | Details ------- ### \_\_construct(ObjectManager $om, ClassMetadata $classMetadata) #### Parameters | | | | | --- | --- | --- | | ObjectManager | $om | | | ClassMetadata | $classMetadata | | ### bool isSingleId() Returns whether the class has a single-column ID. #### Return Value | | | | --- | --- | | bool | returns `true` if the class has a single-column ID and `false` otherwise | ### bool isIntId() Returns whether the class has a single-column integer ID. #### Return Value | | | | --- | --- | | bool | returns `true` if the class has a single-column integer ID and `false` otherwise | ### mixed getIdValue(object $object) Returns the ID value for an object. This method assumes that the object has a single-column ID. #### Parameters | | | | | --- | --- | --- | | object | $object | The object | #### Return Value | | | | --- | --- | | mixed | The ID value | ### string getIdField() Returns the name of the ID field. This method assumes that the object has a single-column ID. #### Return Value | | | | --- | --- | | string | The name of the ID field |
programming_docs
symfony CollectionToArrayTransformer CollectionToArrayTransformer ============================= class **CollectionToArrayTransformer** implements [DataTransformerInterface](../../../../component/form/datatransformerinterface "Symfony\Component\Form\DataTransformerInterface") Methods ------- | | | | | --- | --- | --- | | mixed | [transform](#method_transform)($collection) Transforms a collection into an array. | | | mixed | [reverseTransform](#method_reverseTransform)(mixed $array) Transforms choice keys into entities. | | Details ------- ### mixed transform($collection) Transforms a collection into an array. #### Parameters | | | | | --- | --- | --- | | | $collection | | #### Return Value | | | | --- | --- | | mixed | The value in the transformed representation | #### Exceptions | | | | --- | --- | | [TransformationFailedException](../../../../component/form/exception/transformationfailedexception "Symfony\Component\Form\Exception\TransformationFailedException") | | ### mixed reverseTransform(mixed $array) Transforms choice keys into entities. #### Parameters | | | | | --- | --- | --- | | mixed | $array | An array of entities | #### Return Value | | | | --- | --- | | mixed | The value in the original representation | symfony EntityType EntityType =========== class **EntityType** extends [DoctrineType](doctrinetype "Symfony\Bridge\Doctrine\Form\Type\DoctrineType") Properties ---------- | | | | | | --- | --- | --- | --- | | protected ManagerRegistry | $registry | | from [DoctrineType](doctrinetype#property_registry "Symfony\Bridge\Doctrine\Form\Type\DoctrineType") | Methods ------- | | | | | --- | --- | --- | | | [buildForm](#method_buildForm)([FormBuilderInterface](../../../../component/form/formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") $builder, array $options) Builds the form. | from [DoctrineType](doctrinetype#method_buildForm "Symfony\Bridge\Doctrine\Form\Type\DoctrineType") | | | [buildView](#method_buildView)([FormView](../../../../component/form/formview "Symfony\Component\Form\FormView") $view, [FormInterface](../../../../component/form/forminterface "Symfony\Component\Form\FormInterface") $form, array $options) Builds the form view. | from [AbstractType](../../../../component/form/abstracttype#method_buildView "Symfony\Component\Form\AbstractType") | | | [finishView](#method_finishView)([FormView](../../../../component/form/formview "Symfony\Component\Form\FormView") $view, [FormInterface](../../../../component/form/forminterface "Symfony\Component\Form\FormInterface") $form, array $options) Finishes the form view. | from [AbstractType](../../../../component/form/abstracttype#method_finishView "Symfony\Component\Form\AbstractType") | | | [configureOptions](#method_configureOptions)([OptionsResolver](../../../../component/optionsresolver/optionsresolver "Symfony\Component\OptionsResolver\OptionsResolver") $resolver) Configures the options for this type. | | | string | [getBlockPrefix](#method_getBlockPrefix)() Returns the prefix of the template block name for this type. | | | string|null | [getParent](#method_getParent)() Returns the name of the parent type. | from [DoctrineType](doctrinetype#method_getParent "Symfony\Bridge\Doctrine\Form\Type\DoctrineType") | | static string | [createChoiceLabel](#method_createChoiceLabel)(object $choice) Creates the label for a choice. | from [DoctrineType](doctrinetype#method_createChoiceLabel "Symfony\Bridge\Doctrine\Form\Type\DoctrineType") | | static string | [createChoiceName](#method_createChoiceName)(object $choice, int|string $key, string $value) Creates the field name for a choice. | from [DoctrineType](doctrinetype#method_createChoiceName "Symfony\Bridge\Doctrine\Form\Type\DoctrineType") | | array|false | [getQueryBuilderPartsForCachingHash](#method_getQueryBuilderPartsForCachingHash)(object $queryBuilder) We consider two query builders with an equal SQL string and equal parameters to be equal. | | | | [\_\_construct](#method___construct)(ManagerRegistry $registry) | from [DoctrineType](doctrinetype#method___construct "Symfony\Bridge\Doctrine\Form\Type\DoctrineType") | | [EntityLoaderInterface](../choicelist/entityloaderinterface "Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface") | [getLoader](#method_getLoader)(ObjectManager $manager, mixed $queryBuilder, string $class) Return the default loader object. | | | | [reset](#method_reset)() | from [DoctrineType](doctrinetype#method_reset "Symfony\Bridge\Doctrine\Form\Type\DoctrineType") | Details ------- ### buildForm([FormBuilderInterface](../../../../component/form/formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") $builder, array $options) Builds the form. This method is called for each type in the hierarchy starting from the top most type. Type extensions can further modify the form. #### Parameters | | | | | --- | --- | --- | | [FormBuilderInterface](../../../../component/form/formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") | $builder | The form builder | | array | $options | The options | ### buildView([FormView](../../../../component/form/formview "Symfony\Component\Form\FormView") $view, [FormInterface](../../../../component/form/forminterface "Symfony\Component\Form\FormInterface") $form, array $options) Builds the form view. This method is called for each type in the hierarchy starting from the top most type. Type extensions can further modify the view. A view of a form is built before the views of the child forms are built. This means that you cannot access child views in this method. If you need to do so, move your logic to {@link finishView()} instead. #### Parameters | | | | | --- | --- | --- | | [FormView](../../../../component/form/formview "Symfony\Component\Form\FormView") | $view | The view | | [FormInterface](../../../../component/form/forminterface "Symfony\Component\Form\FormInterface") | $form | The form | | array | $options | The options | ### finishView([FormView](../../../../component/form/formview "Symfony\Component\Form\FormView") $view, [FormInterface](../../../../component/form/forminterface "Symfony\Component\Form\FormInterface") $form, array $options) Finishes the form view. This method gets called for each type in the hierarchy starting from the top most type. Type extensions can further modify the view. When this method is called, views of the form's children have already been built and finished and can be accessed. You should only implement such logic in this method that actually accesses child views. For everything else you are recommended to implement {@link buildView()} instead. #### Parameters | | | | | --- | --- | --- | | [FormView](../../../../component/form/formview "Symfony\Component\Form\FormView") | $view | The view | | [FormInterface](../../../../component/form/forminterface "Symfony\Component\Form\FormInterface") | $form | The form | | array | $options | The options | ### configureOptions([OptionsResolver](../../../../component/optionsresolver/optionsresolver "Symfony\Component\OptionsResolver\OptionsResolver") $resolver) Configures the options for this type. #### Parameters | | | | | --- | --- | --- | | [OptionsResolver](../../../../component/optionsresolver/optionsresolver "Symfony\Component\OptionsResolver\OptionsResolver") | $resolver | The resolver for the options | ### string getBlockPrefix() Returns the prefix of the template block name for this type. The block prefix defaults to the underscored short class name with the "Type" suffix removed (e.g. "UserProfileType" => "user\_profile"). #### Return Value | | | | --- | --- | | string | The prefix of the template block name | ### string|null getParent() Returns the name of the parent type. #### Return Value | | | | --- | --- | | string|null | The name of the parent type if any, null otherwise | ### static string createChoiceLabel(object $choice) Creates the label for a choice. For backwards compatibility, objects are cast to strings by default. #### Parameters | | | | | --- | --- | --- | | object | $choice | The object | #### Return Value | | | | --- | --- | | string | The string representation of the object | ### static string createChoiceName(object $choice, int|string $key, string $value) Creates the field name for a choice. This method is used to generate field names if the underlying object has a single-column integer ID. In that case, the value of the field is the ID of the object. That ID is also used as field name. #### Parameters | | | | | --- | --- | --- | | object | $choice | The object | | int|string | $key | The choice key | | string | $value | The choice value. Corresponds to the object's ID here. | #### Return Value | | | | --- | --- | | string | The field name | ### array|false getQueryBuilderPartsForCachingHash(object $queryBuilder) We consider two query builders with an equal SQL string and equal parameters to be equal. #### Parameters | | | | | --- | --- | --- | | object | $queryBuilder | | #### Return Value | | | | --- | --- | | array|false | Array with important QueryBuilder parts or false if they can't be determined | ### \_\_construct(ManagerRegistry $registry) #### Parameters | | | | | --- | --- | --- | | ManagerRegistry | $registry | | ### [EntityLoaderInterface](../choicelist/entityloaderinterface "Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface") getLoader(ObjectManager $manager, mixed $queryBuilder, string $class) Return the default loader object. #### Parameters | | | | | --- | --- | --- | | ObjectManager | $manager | | | mixed | $queryBuilder | | | string | $class | | #### Return Value | | | | --- | --- | | [EntityLoaderInterface](../choicelist/entityloaderinterface "Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface") | | ### reset() symfony DoctrineType DoctrineType ============= abstract class **DoctrineType** extends [AbstractType](../../../../component/form/abstracttype "Symfony\Component\Form\AbstractType") Properties ---------- | | | | | | --- | --- | --- | --- | | protected ManagerRegistry | $registry | | | Methods ------- | | | | | --- | --- | --- | | | [buildForm](#method_buildForm)([FormBuilderInterface](../../../../component/form/formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") $builder, array $options) Builds the form. | | | | [buildView](#method_buildView)([FormView](../../../../component/form/formview "Symfony\Component\Form\FormView") $view, [FormInterface](../../../../component/form/forminterface "Symfony\Component\Form\FormInterface") $form, array $options) Builds the form view. | from [AbstractType](../../../../component/form/abstracttype#method_buildView "Symfony\Component\Form\AbstractType") | | | [finishView](#method_finishView)([FormView](../../../../component/form/formview "Symfony\Component\Form\FormView") $view, [FormInterface](../../../../component/form/forminterface "Symfony\Component\Form\FormInterface") $form, array $options) Finishes the form view. | from [AbstractType](../../../../component/form/abstracttype#method_finishView "Symfony\Component\Form\AbstractType") | | | [configureOptions](#method_configureOptions)([OptionsResolver](../../../../component/optionsresolver/optionsresolver "Symfony\Component\OptionsResolver\OptionsResolver") $resolver) Configures the options for this type. | | | string | [getBlockPrefix](#method_getBlockPrefix)() Returns the prefix of the template block name for this type. | from [AbstractType](../../../../component/form/abstracttype#method_getBlockPrefix "Symfony\Component\Form\AbstractType") | | string|null | [getParent](#method_getParent)() Returns the name of the parent type. | | | static string | [createChoiceLabel](#method_createChoiceLabel)(object $choice) Creates the label for a choice. | | | static string | [createChoiceName](#method_createChoiceName)(object $choice, int|string $key, string $value) Creates the field name for a choice. | | | array|false | [getQueryBuilderPartsForCachingHash](#method_getQueryBuilderPartsForCachingHash)(object $queryBuilder) Gets important parts from QueryBuilder that will allow to cache its results. | | | | [\_\_construct](#method___construct)(ManagerRegistry $registry) | | | [EntityLoaderInterface](../choicelist/entityloaderinterface "Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface") | [getLoader](#method_getLoader)(ObjectManager $manager, mixed $queryBuilder, string $class) Return the default loader object. | | | | [reset](#method_reset)() | | Details ------- ### buildForm([FormBuilderInterface](../../../../component/form/formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") $builder, array $options) Builds the form. This method is called for each type in the hierarchy starting from the top most type. Type extensions can further modify the form. #### Parameters | | | | | --- | --- | --- | | [FormBuilderInterface](../../../../component/form/formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") | $builder | The form builder | | array | $options | The options | ### buildView([FormView](../../../../component/form/formview "Symfony\Component\Form\FormView") $view, [FormInterface](../../../../component/form/forminterface "Symfony\Component\Form\FormInterface") $form, array $options) Builds the form view. This method is called for each type in the hierarchy starting from the top most type. Type extensions can further modify the view. A view of a form is built before the views of the child forms are built. This means that you cannot access child views in this method. If you need to do so, move your logic to {@link finishView()} instead. #### Parameters | | | | | --- | --- | --- | | [FormView](../../../../component/form/formview "Symfony\Component\Form\FormView") | $view | The view | | [FormInterface](../../../../component/form/forminterface "Symfony\Component\Form\FormInterface") | $form | The form | | array | $options | The options | ### finishView([FormView](../../../../component/form/formview "Symfony\Component\Form\FormView") $view, [FormInterface](../../../../component/form/forminterface "Symfony\Component\Form\FormInterface") $form, array $options) Finishes the form view. This method gets called for each type in the hierarchy starting from the top most type. Type extensions can further modify the view. When this method is called, views of the form's children have already been built and finished and can be accessed. You should only implement such logic in this method that actually accesses child views. For everything else you are recommended to implement {@link buildView()} instead. #### Parameters | | | | | --- | --- | --- | | [FormView](../../../../component/form/formview "Symfony\Component\Form\FormView") | $view | The view | | [FormInterface](../../../../component/form/forminterface "Symfony\Component\Form\FormInterface") | $form | The form | | array | $options | The options | ### configureOptions([OptionsResolver](../../../../component/optionsresolver/optionsresolver "Symfony\Component\OptionsResolver\OptionsResolver") $resolver) Configures the options for this type. #### Parameters | | | | | --- | --- | --- | | [OptionsResolver](../../../../component/optionsresolver/optionsresolver "Symfony\Component\OptionsResolver\OptionsResolver") | $resolver | The resolver for the options | ### string getBlockPrefix() Returns the prefix of the template block name for this type. The block prefix defaults to the underscored short class name with the "Type" suffix removed (e.g. "UserProfileType" => "user\_profile"). #### Return Value | | | | --- | --- | | string | The prefix of the template block name | ### string|null getParent() Returns the name of the parent type. #### Return Value | | | | --- | --- | | string|null | The name of the parent type if any, null otherwise | ### static string createChoiceLabel(object $choice) Creates the label for a choice. For backwards compatibility, objects are cast to strings by default. #### Parameters | | | | | --- | --- | --- | | object | $choice | The object | #### Return Value | | | | --- | --- | | string | The string representation of the object | ### static string createChoiceName(object $choice, int|string $key, string $value) Creates the field name for a choice. This method is used to generate field names if the underlying object has a single-column integer ID. In that case, the value of the field is the ID of the object. That ID is also used as field name. #### Parameters | | | | | --- | --- | --- | | object | $choice | The object | | int|string | $key | The choice key | | string | $value | The choice value. Corresponds to the object's ID here. | #### Return Value | | | | --- | --- | | string | The field name | ### array|false getQueryBuilderPartsForCachingHash(object $queryBuilder) Gets important parts from QueryBuilder that will allow to cache its results. For instance in ORM two query builders with an equal SQL string and equal parameters are considered to be equal. #### Parameters | | | | | --- | --- | --- | | object | $queryBuilder | | #### Return Value | | | | --- | --- | | array|false | Array with important QueryBuilder parts or false if they can't be determined | ### \_\_construct(ManagerRegistry $registry) #### Parameters | | | | | --- | --- | --- | | ManagerRegistry | $registry | | ### abstract [EntityLoaderInterface](../choicelist/entityloaderinterface "Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface") getLoader(ObjectManager $manager, mixed $queryBuilder, string $class) Return the default loader object. #### Parameters | | | | | --- | --- | --- | | ObjectManager | $manager | | | mixed | $queryBuilder | | | string | $class | | #### Return Value | | | | --- | --- | | [EntityLoaderInterface](../choicelist/entityloaderinterface "Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface") | | ### reset() symfony MergeDoctrineCollectionListener MergeDoctrineCollectionListener ================================ class **MergeDoctrineCollectionListener** implements [EventSubscriberInterface](../../../../component/eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") Merge changes from the request to a Doctrine\Common\Collections\Collection instance. This works with ORM, MongoDB and CouchDB instances of the collection interface. Methods ------- | | | | | --- | --- | --- | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | | | | [onSubmit](#method_onSubmit)([FormEvent](../../../../component/form/formevent "Symfony\Component\Form\FormEvent") $event) | | Details ------- ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to | ### onSubmit([FormEvent](../../../../component/form/formevent "Symfony\Component\Form\FormEvent") $event) #### Parameters | | | | | --- | --- | --- | | [FormEvent](../../../../component/form/formevent "Symfony\Component\Form\FormEvent") | $event | |
programming_docs
symfony Symfony\Bridge\Doctrine\Validator\Constraints Symfony\Bridge\Doctrine\Validator\Constraints ============================================= Classes ------- | | | | --- | --- | | [UniqueEntity](constraints/uniqueentity "Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity") | Constraint for the Unique Entity validator. | | [UniqueEntityValidator](constraints/uniqueentityvalidator "Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator") | Unique Entity Validator checks if one or a set of fields contain unique values. | symfony DoctrineInitializer DoctrineInitializer ==================== class **DoctrineInitializer** implements [ObjectInitializerInterface](../../../component/validator/objectinitializerinterface "Symfony\Component\Validator\ObjectInitializerInterface") Automatically loads proxy object before validation. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $registry | | | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(ManagerRegistry $registry) | | | | [initialize](#method_initialize)(object $object) Initializes an object just before validation. | | Details ------- ### \_\_construct(ManagerRegistry $registry) #### Parameters | | | | | --- | --- | --- | | ManagerRegistry | $registry | | ### initialize(object $object) Initializes an object just before validation. #### Parameters | | | | | --- | --- | --- | | object | $object | The object to validate | symfony UniqueEntity UniqueEntity ============= class **UniqueEntity** extends [Constraint](../../../../component/validator/constraint "Symfony\Component\Validator\Constraint") Constraint for the Unique Entity validator. Constants --------- | | | | --- | --- | | DEFAULT\_GROUP | *The name of the group given to all constraints with no explicit group.* | | CLASS\_CONSTRAINT | *Marks a constraint that can be put onto classes.* | | PROPERTY\_CONSTRAINT | *Marks a constraint that can be put onto properties.* | | NOT\_UNIQUE\_ERROR | | Properties ---------- | | | | | | --- | --- | --- | --- | | static protected | $errorNames | | | | mixed | $payload | Domain-specific data attached to a constraint. | from [Constraint](../../../../component/validator/constraint#property_payload "Symfony\Component\Validator\Constraint") | | array | $groups | The groups that the constraint belongs to | from [Constraint](../../../../component/validator/constraint#property_groups "Symfony\Component\Validator\Constraint") | | | $message | | | | | $service | | | | | $em | | | | | $entityClass | | | | | $repositoryMethod | | | | | $fields | | | | | $errorPath | | | | | $ignoreNull | | | Methods ------- | | | | | --- | --- | --- | | static string | [getErrorName](#method_getErrorName)(string $errorCode) Returns the name of the given error code. | from [Constraint](../../../../component/validator/constraint#method_getErrorName "Symfony\Component\Validator\Constraint") | | | [\_\_construct](#method___construct)(mixed $options = null) Initializes the constraint with options. | from [Constraint](../../../../component/validator/constraint#method___construct "Symfony\Component\Validator\Constraint") | | | [\_\_set](#method___set)(string $option, mixed $value) Sets the value of a lazily initialized option. | from [Constraint](../../../../component/validator/constraint#method___set "Symfony\Component\Validator\Constraint") | | mixed | [\_\_get](#method___get)(string $option) Returns the value of a lazily initialized option. | from [Constraint](../../../../component/validator/constraint#method___get "Symfony\Component\Validator\Constraint") | | bool | [\_\_isset](#method___isset)(string $option) | from [Constraint](../../../../component/validator/constraint#method___isset "Symfony\Component\Validator\Constraint") | | | [addImplicitGroupName](#method_addImplicitGroupName)(string $group) Adds the given group if this constraint is in the Default group. | from [Constraint](../../../../component/validator/constraint#method_addImplicitGroupName "Symfony\Component\Validator\Constraint") | | string | [getDefaultOption](#method_getDefaultOption)() Returns the name of the default option. | | | array | [getRequiredOptions](#method_getRequiredOptions)() Returns the name of the required options. | | | string | [validatedBy](#method_validatedBy)() The validator must be defined as a service with this name. | | | string|array | [getTargets](#method_getTargets)() Returns whether the constraint can be put onto classes, properties or both. | | | array | [\_\_sleep](#method___sleep)() Optimizes the serialized value to minimize storage space. | from [Constraint](../../../../component/validator/constraint#method___sleep "Symfony\Component\Validator\Constraint") | Details ------- ### static string getErrorName(string $errorCode) Returns the name of the given error code. #### Parameters | | | | | --- | --- | --- | | string | $errorCode | The error code | #### Return Value | | | | --- | --- | | string | The name of the error code | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](../../../../component/validator/exception/invalidargumentexception "Symfony\Component\Validator\Exception\InvalidArgumentException") | If the error code does not exist | ### \_\_construct(mixed $options = null) Initializes the constraint with options. You should pass an associative array. The keys should be the names of existing properties in this class. The values should be the value for these properties. Alternatively you can override the method getDefaultOption() to return the name of an existing property. If no associative array is passed, this property is set instead. You can force that certain options are set by overriding getRequiredOptions() to return the names of these options. If any option is not set here, an exception is thrown. #### Parameters | | | | | --- | --- | --- | | mixed | $options | The options (as associative array) or the value for the default option (any other type) | #### Exceptions | | | | --- | --- | | [InvalidOptionsException](../../../../component/validator/exception/invalidoptionsexception "Symfony\Component\Validator\Exception\InvalidOptionsException") | When you pass the names of non-existing options | | [MissingOptionsException](../../../../component/validator/exception/missingoptionsexception "Symfony\Component\Validator\Exception\MissingOptionsException") | When you don't pass any of the options returned by getRequiredOptions() | | [ConstraintDefinitionException](../../../../component/validator/exception/constraintdefinitionexception "Symfony\Component\Validator\Exception\ConstraintDefinitionException") | When you don't pass an associative array, but getDefaultOption() returns null | ### \_\_set(string $option, mixed $value) Sets the value of a lazily initialized option. Corresponding properties are added to the object on first access. Hence this method will be called at most once per constraint instance and option name. #### Parameters | | | | | --- | --- | --- | | string | $option | The option name | | mixed | $value | The value to set | #### Exceptions | | | | --- | --- | | [InvalidOptionsException](../../../../component/validator/exception/invalidoptionsexception "Symfony\Component\Validator\Exception\InvalidOptionsException") | If an invalid option name is given | ### mixed \_\_get(string $option) Returns the value of a lazily initialized option. Corresponding properties are added to the object on first access. Hence this method will be called at most once per constraint instance and option name. #### Parameters | | | | | --- | --- | --- | | string | $option | The option name | #### Return Value | | | | --- | --- | | mixed | The value of the option | #### Exceptions | | | | --- | --- | | [InvalidOptionsException](../../../../component/validator/exception/invalidoptionsexception "Symfony\Component\Validator\Exception\InvalidOptionsException") | If an invalid option name is given | ### bool \_\_isset(string $option) #### Parameters | | | | | --- | --- | --- | | string | $option | The option name | #### Return Value | | | | --- | --- | | bool | | ### addImplicitGroupName(string $group) Adds the given group if this constraint is in the Default group. #### Parameters | | | | | --- | --- | --- | | string | $group | | ### string getDefaultOption() Returns the name of the default option. Override this method to define a default option. #### Return Value | | | | --- | --- | | string | | ### array getRequiredOptions() Returns the name of the required options. Override this method if you want to define required options. #### Return Value | | | | --- | --- | | array | | ### string validatedBy() The validator must be defined as a service with this name. #### Return Value | | | | --- | --- | | string | | ### string|array getTargets() Returns whether the constraint can be put onto classes, properties or both. This method should return one or more of the constants Constraint::CLASS\_CONSTRAINT and Constraint::PROPERTY\_CONSTRAINT. #### Return Value | | | | --- | --- | | string|array | One or more constant values | ### array \_\_sleep() Optimizes the serialized value to minimize storage space. #### Return Value | | | | --- | --- | | array | The properties to serialize | symfony UniqueEntityValidator UniqueEntityValidator ====================== class **UniqueEntityValidator** extends [ConstraintValidator](../../../../component/validator/constraintvalidator "Symfony\Component\Validator\ConstraintValidator") Unique Entity Validator checks if one or a set of fields contain unique values. Constants --------- | | | | --- | --- | | PRETTY\_DATE | *Whether to format {@link \DateTime} objects as RFC-3339 dates ("Y-m-d H:i:s").* | | OBJECT\_TO\_STRING | *Whether to cast objects with a "\_\_toString()" method to strings.* | Properties ---------- | | | | | | --- | --- | --- | --- | | protected [ExecutionContextInterface](../../../../component/validator/context/executioncontextinterface "Symfony\Component\Validator\Context\ExecutionContextInterface") | $context | | from [ConstraintValidator](../../../../component/validator/constraintvalidator#property_context "Symfony\Component\Validator\ConstraintValidator") | Methods ------- | | | | | --- | --- | --- | | | [initialize](#method_initialize)([ExecutionContextInterface](../../../../component/validator/context/executioncontextinterface "Symfony\Component\Validator\Context\ExecutionContextInterface") $context) Initializes the constraint validator. | from [ConstraintValidator](../../../../component/validator/constraintvalidator#method_initialize "Symfony\Component\Validator\ConstraintValidator") | | string | [formatTypeOf](#method_formatTypeOf)(mixed $value) Returns a string representation of the type of the value. | from [ConstraintValidator](../../../../component/validator/constraintvalidator#method_formatTypeOf "Symfony\Component\Validator\ConstraintValidator") | | string | [formatValue](#method_formatValue)(mixed $value, int $format = 0) Returns a string representation of the value. | from [ConstraintValidator](../../../../component/validator/constraintvalidator#method_formatValue "Symfony\Component\Validator\ConstraintValidator") | | string | [formatValues](#method_formatValues)(array $values, int $format = 0) Returns a string representation of a list of values. | from [ConstraintValidator](../../../../component/validator/constraintvalidator#method_formatValues "Symfony\Component\Validator\ConstraintValidator") | | | [\_\_construct](#method___construct)(ManagerRegistry $registry) | | | | [validate](#method_validate)(object $entity, [Constraint](../../../../component/validator/constraint "Symfony\Component\Validator\Constraint") $constraint) | | Details ------- ### initialize([ExecutionContextInterface](../../../../component/validator/context/executioncontextinterface "Symfony\Component\Validator\Context\ExecutionContextInterface") $context) Initializes the constraint validator. #### Parameters | | | | | --- | --- | --- | | [ExecutionContextInterface](../../../../component/validator/context/executioncontextinterface "Symfony\Component\Validator\Context\ExecutionContextInterface") | $context | The current validation context | ### protected string formatTypeOf(mixed $value) Returns a string representation of the type of the value. This method should be used if you pass the type of a value as message parameter to a constraint violation. Note that such parameters should usually not be included in messages aimed at non-technical people. #### Parameters | | | | | --- | --- | --- | | mixed | $value | The value to return the type of | #### Return Value | | | | --- | --- | | string | The type of the value | ### protected string formatValue(mixed $value, int $format = 0) Returns a string representation of the value. This method returns the equivalent PHP tokens for most scalar types (i.e. "false" for false, "1" for 1 etc.). Strings are always wrapped in double quotes ("). Objects, arrays and resources are formatted as "object", "array" and "resource". If the $format bitmask contains the PRETTY\_DATE bit, then {@link \DateTime} objects will be formatted as RFC-3339 dates ("Y-m-d H:i:s"). Be careful when passing message parameters to a constraint violation that (may) contain objects, arrays or resources. These parameters should only be displayed for technical users. Non-technical users won't know what an "object", "array" or "resource" is and will be confused by the violation message. #### Parameters | | | | | --- | --- | --- | | mixed | $value | The value to format as string | | int | $format | A bitwise combination of the format constants in this class | #### Return Value | | | | --- | --- | | string | The string representation of the passed value | ### protected string formatValues(array $values, int $format = 0) Returns a string representation of a list of values. Each of the values is converted to a string using {@link formatValue()}. The values are then concatenated with commas. #### Parameters | | | | | --- | --- | --- | | array | $values | A list of values | | int | $format | A bitwise combination of the format constants in this class | #### Return Value | | | | --- | --- | | string | The string representation of the value list | #### See also | | | | --- | --- | | formatValue() | | ### \_\_construct(ManagerRegistry $registry) #### Parameters | | | | | --- | --- | --- | | ManagerRegistry | $registry | | ### validate(object $entity, [Constraint](../../../../component/validator/constraint "Symfony\Component\Validator\Constraint") $constraint) #### Parameters | | | | | --- | --- | --- | | object | $entity | | | [Constraint](../../../../component/validator/constraint "Symfony\Component\Validator\Constraint") | $constraint | The constraint for the validation | #### Exceptions | | | | --- | --- | | [UnexpectedTypeException](../../../../component/validator/exception/unexpectedtypeexception "Symfony\Component\Validator\Exception\UnexpectedTypeException") | | | [ConstraintDefinitionException](../../../../component/validator/exception/constraintdefinitionexception "Symfony\Component\Validator\Exception\ConstraintDefinitionException") | | symfony DbalLogger DbalLogger =========== class **DbalLogger** implements SQLLogger Constants --------- | | | | --- | --- | | MAX\_STRING\_LENGTH | | | BINARY\_DATA\_VALUE | | Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $logger | | | | protected | $stopwatch | | | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(LoggerInterface $logger = null, [Stopwatch](../../../component/stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") $stopwatch = null) | | | | [startQuery](#method_startQuery)($sql, array $params = null, array $types = null) {@inheritdoc} | | | | [stopQuery](#method_stopQuery)() {@inheritdoc} | | | | [log](#method_log)(string $message, array $params) Logs a message. | | Details ------- ### \_\_construct(LoggerInterface $logger = null, [Stopwatch](../../../component/stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") $stopwatch = null) #### Parameters | | | | | --- | --- | --- | | LoggerInterface | $logger | | | [Stopwatch](../../../component/stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") | $stopwatch | | ### startQuery($sql, array $params = null, array $types = null) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | | $sql | | | array | $params | | | array | $types | | ### stopQuery() {@inheritdoc} ### protected log(string $message, array $params) Logs a message. #### Parameters | | | | | --- | --- | --- | | string | $message | A message to log | | array | $params | The context | symfony DoctrineTestHelper DoctrineTestHelper =================== class **DoctrineTestHelper** Provides utility functions needed in tests. Methods ------- | | | | | --- | --- | --- | | static EntityManager | [createTestEntityManager](#method_createTestEntityManager)(Configuration $config = null) Returns an entity manager for testing. | | | static Configuration | [createTestConfiguration](#method_createTestConfiguration)() | | Details ------- ### static EntityManager createTestEntityManager(Configuration $config = null) Returns an entity manager for testing. #### Parameters | | | | | --- | --- | --- | | Configuration | $config | | #### Return Value | | | | --- | --- | | EntityManager | | ### static Configuration createTestConfiguration() #### Return Value | | | | --- | --- | | Configuration | | symfony TestRepositoryFactory TestRepositoryFactory ====================== class **TestRepositoryFactory** implements RepositoryFactory Methods ------- | | | | | --- | --- | --- | | | [getRepository](#method_getRepository)(EntityManagerInterface $entityManager, $entityName) {@inheritdoc} | | | | [setRepository](#method_setRepository)(EntityManagerInterface $entityManager, $entityName, ObjectRepository $repository) | | Details ------- ### getRepository(EntityManagerInterface $entityManager, $entityName) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | EntityManagerInterface | $entityManager | | | | $entityName | | ### setRepository(EntityManagerInterface $entityManager, $entityName, ObjectRepository $repository) #### Parameters | | | | | --- | --- | --- | | EntityManagerInterface | $entityManager | | | | $entityName | | | ObjectRepository | $repository | | symfony Symfony\Bridge\Doctrine\Security\User Symfony\Bridge\Doctrine\Security\User ===================================== Classes ------- | | | | --- | --- | | [EntityUserProvider](user/entityuserprovider "Symfony\Bridge\Doctrine\Security\User\EntityUserProvider") | Wrapper around a Doctrine ObjectManager. | Interfaces ---------- | | | | --- | --- | | *[UserLoaderInterface](user/userloaderinterface "Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface")* | Represents a class that loads UserInterface objects from Doctrine source for the authentication system. | symfony Symfony\Bridge\Doctrine\Security\RememberMe Symfony\Bridge\Doctrine\Security\RememberMe =========================================== Classes ------- | | | | --- | --- | | [DoctrineTokenProvider](rememberme/doctrinetokenprovider "Symfony\Bridge\Doctrine\Security\RememberMe\DoctrineTokenProvider") | This class provides storage for the tokens that is set in "remember me" cookies. This way no password secrets will be stored in the cookies on the client machine, and thus the security is improved. |
programming_docs
symfony UserLoaderInterface UserLoaderInterface ==================== interface **UserLoaderInterface** Represents a class that loads UserInterface objects from Doctrine source for the authentication system. This interface is meant to facilitate the loading of a User from Doctrine source using a custom method. If you want to implement your own logic of retrieving the user from Doctrine your repository should implement this interface. Methods ------- | | | | | --- | --- | --- | | [UserInterface](../../../../component/security/core/user/userinterface "Symfony\Component\Security\Core\User\UserInterface")|null | [loadUserByUsername](#method_loadUserByUsername)(string $username) Loads the user for the given username. | | Details ------- ### [UserInterface](../../../../component/security/core/user/userinterface "Symfony\Component\Security\Core\User\UserInterface")|null loadUserByUsername(string $username) Loads the user for the given username. This method must return null if the user is not found. #### Parameters | | | | | --- | --- | --- | | string | $username | The username | #### Return Value | | | | --- | --- | | [UserInterface](../../../../component/security/core/user/userinterface "Symfony\Component\Security\Core\User\UserInterface")|null | | symfony EntityUserProvider EntityUserProvider =================== class **EntityUserProvider** implements [UserProviderInterface](../../../../component/security/core/user/userproviderinterface "Symfony\Component\Security\Core\User\UserProviderInterface") Wrapper around a Doctrine ObjectManager. Provides easy to use provisioning for Doctrine entity users. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(ManagerRegistry $registry, string $classOrAlias, string $property = null, string $managerName = null) | | | [UserInterface](../../../../component/security/core/user/userinterface "Symfony\Component\Security\Core\User\UserInterface") | [loadUserByUsername](#method_loadUserByUsername)(string $username) Loads the user for the given username. | | | [UserInterface](../../../../component/security/core/user/userinterface "Symfony\Component\Security\Core\User\UserInterface") | [refreshUser](#method_refreshUser)([UserInterface](../../../../component/security/core/user/userinterface "Symfony\Component\Security\Core\User\UserInterface") $user) Refreshes the user. | | | bool | [supportsClass](#method_supportsClass)(string $class) Whether this provider supports the given user class. | | Details ------- ### \_\_construct(ManagerRegistry $registry, string $classOrAlias, string $property = null, string $managerName = null) #### Parameters | | | | | --- | --- | --- | | ManagerRegistry | $registry | | | string | $classOrAlias | | | string | $property | | | string | $managerName | | ### [UserInterface](../../../../component/security/core/user/userinterface "Symfony\Component\Security\Core\User\UserInterface") loadUserByUsername(string $username) Loads the user for the given username. This method must throw UsernameNotFoundException if the user is not found. #### Parameters | | | | | --- | --- | --- | | string | $username | The username | #### Return Value | | | | --- | --- | | [UserInterface](../../../../component/security/core/user/userinterface "Symfony\Component\Security\Core\User\UserInterface") | | #### Exceptions | | | | --- | --- | | [UsernameNotFoundException](../../../../component/security/core/exception/usernamenotfoundexception "Symfony\Component\Security\Core\Exception\UsernameNotFoundException") | if the user is not found | ### [UserInterface](../../../../component/security/core/user/userinterface "Symfony\Component\Security\Core\User\UserInterface") refreshUser([UserInterface](../../../../component/security/core/user/userinterface "Symfony\Component\Security\Core\User\UserInterface") $user) Refreshes the user. It is up to the implementation to decide if the user data should be totally reloaded (e.g. from the database), or if the UserInterface object can just be merged into some internal array of users / identity map. #### Parameters | | | | | --- | --- | --- | | [UserInterface](../../../../component/security/core/user/userinterface "Symfony\Component\Security\Core\User\UserInterface") | $user | | #### Return Value | | | | --- | --- | | [UserInterface](../../../../component/security/core/user/userinterface "Symfony\Component\Security\Core\User\UserInterface") | | #### Exceptions | | | | --- | --- | | [UnsupportedUserException](../../../../component/security/core/exception/unsupporteduserexception "Symfony\Component\Security\Core\Exception\UnsupportedUserException") | if the user is not supported | | [UsernameNotFoundException](../../../../component/security/core/exception/usernamenotfoundexception "Symfony\Component\Security\Core\Exception\UsernameNotFoundException") | if the user is not found | ### bool supportsClass(string $class) Whether this provider supports the given user class. #### Parameters | | | | | --- | --- | --- | | string | $class | | #### Return Value | | | | --- | --- | | bool | | symfony DoctrineTokenProvider DoctrineTokenProvider ====================== class **DoctrineTokenProvider** implements [TokenProviderInterface](../../../../component/security/core/authentication/rememberme/tokenproviderinterface "Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface") This class provides storage for the tokens that is set in "remember me" cookies. This way no password secrets will be stored in the cookies on the client machine, and thus the security is improved. This depends only on doctrine in order to get a database connection and to do the conversion of the datetime column. In order to use this class, you need the following table in your database: ``` CREATE TABLE `rememberme_token` ( `series` char(88) UNIQUE PRIMARY KEY NOT NULL, `value` char(88) NOT NULL, `lastUsed` datetime NOT NULL, `class` varchar(100) NOT NULL, `username` varchar(200) NOT NULL ); ``` Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(Connection $conn) | | | [PersistentTokenInterface](../../../../component/security/core/authentication/rememberme/persistenttokeninterface "Symfony\Component\Security\Core\Authentication\RememberMe\PersistentTokenInterface") | [loadTokenBySeries](#method_loadTokenBySeries)(string $series) Loads the active token for the given series. | | | | [deleteTokenBySeries](#method_deleteTokenBySeries)(string $series) Deletes all tokens belonging to series. | | | | [updateToken](#method_updateToken)(string $series, string $tokenValue, [DateTime](http://php.net/DateTime) $lastUsed) Updates the token according to this data. | | | | [createNewToken](#method_createNewToken)([PersistentTokenInterface](../../../../component/security/core/authentication/rememberme/persistenttokeninterface "Symfony\Component\Security\Core\Authentication\RememberMe\PersistentTokenInterface") $token) Creates a new token. | | Details ------- ### \_\_construct(Connection $conn) #### Parameters | | | | | --- | --- | --- | | Connection | $conn | | ### [PersistentTokenInterface](../../../../component/security/core/authentication/rememberme/persistenttokeninterface "Symfony\Component\Security\Core\Authentication\RememberMe\PersistentTokenInterface") loadTokenBySeries(string $series) Loads the active token for the given series. #### Parameters | | | | | --- | --- | --- | | string | $series | | #### Return Value | | | | --- | --- | | [PersistentTokenInterface](../../../../component/security/core/authentication/rememberme/persistenttokeninterface "Symfony\Component\Security\Core\Authentication\RememberMe\PersistentTokenInterface") | | #### Exceptions | | | | --- | --- | | [TokenNotFoundException](../../../../component/security/core/exception/tokennotfoundexception "Symfony\Component\Security\Core\Exception\TokenNotFoundException") | if the token is not found | ### deleteTokenBySeries(string $series) Deletes all tokens belonging to series. #### Parameters | | | | | --- | --- | --- | | string | $series | | ### updateToken(string $series, string $tokenValue, [DateTime](http://php.net/DateTime) $lastUsed) Updates the token according to this data. #### Parameters | | | | | --- | --- | --- | | string | $series | | | string | $tokenValue | | | [DateTime](http://php.net/DateTime) | $lastUsed | | #### Exceptions | | | | --- | --- | | [TokenNotFoundException](../../../../component/security/core/exception/tokennotfoundexception "Symfony\Component\Security\Core\Exception\TokenNotFoundException") | if the token is not found | ### createNewToken([PersistentTokenInterface](../../../../component/security/core/authentication/rememberme/persistenttokeninterface "Symfony\Component\Security\Core\Authentication\RememberMe\PersistentTokenInterface") $token) Creates a new token. #### Parameters | | | | | --- | --- | --- | | [PersistentTokenInterface](../../../../component/security/core/authentication/rememberme/persistenttokeninterface "Symfony\Component\Security\Core\Authentication\RememberMe\PersistentTokenInterface") | $token | | symfony DoctrineExtractor DoctrineExtractor ================== class **DoctrineExtractor** implements [PropertyListExtractorInterface](../../../component/propertyinfo/propertylistextractorinterface "Symfony\Component\PropertyInfo\PropertyListExtractorInterface"), [PropertyTypeExtractorInterface](../../../component/propertyinfo/propertytypeextractorinterface "Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface") Extracts data using Doctrine ORM and ODM metadata. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(ClassMetadataFactory $classMetadataFactory) | | | string[]|null | [getProperties](#method_getProperties)(string $class, array $context = array()) Gets the list of properties available for the given class. | | | [Type](../../../component/propertyinfo/type "Symfony\Component\PropertyInfo\Type")[]|null | [getTypes](#method_getTypes)(string $class, string $property, array $context = array()) Gets types of a property. | | Details ------- ### \_\_construct(ClassMetadataFactory $classMetadataFactory) #### Parameters | | | | | --- | --- | --- | | ClassMetadataFactory | $classMetadataFactory | | ### string[]|null getProperties(string $class, array $context = array()) Gets the list of properties available for the given class. #### Parameters | | | | | --- | --- | --- | | string | $class | | | array | $context | | #### Return Value | | | | --- | --- | | string[]|null | | ### [Type](../../../component/propertyinfo/type "Symfony\Component\PropertyInfo\Type")[]|null getTypes(string $class, string $property, array $context = array()) Gets types of a property. #### Parameters | | | | | --- | --- | --- | | string | $class | | | string | $property | | | array | $context | | #### Return Value | | | | --- | --- | | [Type](../../../component/propertyinfo/type "Symfony\Component\PropertyInfo\Type")[]|null | | symfony ContainerAwareLoader ContainerAwareLoader ===================== class **ContainerAwareLoader** extends Loader Doctrine data fixtures loader that injects the service container into fixture objects that implement ContainerAwareInterface. Note: Use of this class requires the Doctrine data fixtures extension, which is a suggested dependency for Symfony. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([ContainerInterface](../../../component/dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface") $container) | | | | [addFixture](#method_addFixture)(FixtureInterface $fixture) {@inheritdoc} | | Details ------- ### \_\_construct([ContainerInterface](../../../component/dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface") $container) #### Parameters | | | | | --- | --- | --- | | [ContainerInterface](../../../component/dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface") | $container | | ### addFixture(FixtureInterface $fixture) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | FixtureInterface | $fixture | | symfony ProxyCacheWarmer ProxyCacheWarmer ================= class **ProxyCacheWarmer** implements [CacheWarmerInterface](../../../component/httpkernel/cachewarmer/cachewarmerinterface "Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface") The proxy generator cache warmer generates all entity proxies. In the process of generating proxies the cache for all the metadata is primed also, since this information is necessary to build the proxies in the first place. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(ManagerRegistry $registry) | | | bool | [isOptional](#method_isOptional)() This cache warmer is not optional, without proxies fatal error occurs! | | | | [warmUp](#method_warmUp)(string $cacheDir) Warms up the cache. | | Details ------- ### \_\_construct(ManagerRegistry $registry) #### Parameters | | | | | --- | --- | --- | | ManagerRegistry | $registry | | ### bool isOptional() This cache warmer is not optional, without proxies fatal error occurs! #### Return Value | | | | --- | --- | | bool | true if the warmer is optional, false otherwise | ### warmUp(string $cacheDir) Warms up the cache. #### Parameters | | | | | --- | --- | --- | | string | $cacheDir | The cache directory | symfony DoctrineTransactionMiddleware DoctrineTransactionMiddleware ============================== class **DoctrineTransactionMiddleware** implements [MiddlewareInterface](../../../component/messenger/middleware/middlewareinterface "Symfony\Component\Messenger\Middleware\MiddlewareInterface") Wraps all handlers in a single doctrine transaction. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(ManagerRegistry $managerRegistry, string|null $entityManagerName) | | | mixed | [handle](#method_handle)($message, callable $next) | | Details ------- ### \_\_construct(ManagerRegistry $managerRegistry, string|null $entityManagerName) #### Parameters | | | | | --- | --- | --- | | ManagerRegistry | $managerRegistry | | | string|null | $entityManagerName | | ### mixed handle($message, callable $next) #### Parameters | | | | | --- | --- | --- | | | $message | | | callable | $next | | #### Return Value | | | | --- | --- | | mixed | | symfony DoctrineTransactionMiddlewareFactory DoctrineTransactionMiddlewareFactory ===================================== class **DoctrineTransactionMiddlewareFactory** Create a Doctrine ORM transaction middleware to be used in a message bus from an entity manager name. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([ManagerRegistry](../managerregistry "Symfony\Bridge\Doctrine\ManagerRegistry") $managerRegistry) | | | [DoctrineTransactionMiddleware](doctrinetransactionmiddleware "Symfony\Bridge\Doctrine\Messenger\DoctrineTransactionMiddleware") | [createMiddleware](#method_createMiddleware)(string $managerName) | | Details ------- ### \_\_construct([ManagerRegistry](../managerregistry "Symfony\Bridge\Doctrine\ManagerRegistry") $managerRegistry) #### Parameters | | | | | --- | --- | --- | | [ManagerRegistry](../managerregistry "Symfony\Bridge\Doctrine\ManagerRegistry") | $managerRegistry | | ### [DoctrineTransactionMiddleware](doctrinetransactionmiddleware "Symfony\Bridge\Doctrine\Messenger\DoctrineTransactionMiddleware") createMiddleware(string $managerName) #### Parameters | | | | | --- | --- | --- | | string | $managerName | | #### Return Value | | | | --- | --- | | [DoctrineTransactionMiddleware](doctrinetransactionmiddleware "Symfony\Bridge\Doctrine\Messenger\DoctrineTransactionMiddleware") | | symfony Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass ======================================================== Classes ------- | | | | --- | --- | | [DoctrineValidationPass](compilerpass/doctrinevalidationpass "Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\DoctrineValidationPass") | Registers additional validators. | | [RegisterEventListenersAndSubscribersPass](compilerpass/registereventlistenersandsubscriberspass "Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\RegisterEventListenersAndSubscribersPass") | Registers event listeners and subscribers to the available doctrine connections. | | [RegisterMappingsPass](compilerpass/registermappingspass "Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\RegisterMappingsPass") | Base class for the doctrine bundles to provide a compiler pass class that helps to register doctrine mappings. | symfony Symfony\Bridge\Doctrine\DependencyInjection\Security Symfony\Bridge\Doctrine\DependencyInjection\Security ==================================================== Namespaces ---------- [Symfony\Bridge\Doctrine\DependencyInjection\Security\UserProvider](security/userprovider) symfony AbstractDoctrineExtension AbstractDoctrineExtension ========================== abstract class **AbstractDoctrineExtension** extends [Extension](../../../component/httpkernel/dependencyinjection/extension "Symfony\Component\HttpKernel\DependencyInjection\Extension") This abstract classes groups common code that Doctrine Object Manager extensions (ORM, MongoDB, CouchDB) need. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $aliasMap | Used inside metadata driver method to simplify aggregation of data. | | | protected | $drivers | Used inside metadata driver method to simplify aggregation of data. | | Methods ------- | | | | | --- | --- | --- | | string | [getXsdValidationBasePath](#method_getXsdValidationBasePath)() Returns the base path for the XSD files. | from [Extension](../../../component/dependencyinjection/extension/extension#method_getXsdValidationBasePath "Symfony\Component\DependencyInjection\Extension\Extension") | | string | [getNamespace](#method_getNamespace)() Returns the namespace to be used for this extension (XML namespace). | from [Extension](../../../component/dependencyinjection/extension/extension#method_getNamespace "Symfony\Component\DependencyInjection\Extension\Extension") | | string | [getAlias](#method_getAlias)() Returns the recommended alias to use in XML. | from [Extension](../../../component/dependencyinjection/extension/extension#method_getAlias "Symfony\Component\DependencyInjection\Extension\Extension") | | [ConfigurationInterface](../../../component/config/definition/configurationinterface "Symfony\Component\Config\Definition\ConfigurationInterface")|null | [getConfiguration](#method_getConfiguration)(array $config, [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Returns extension configuration. | from [Extension](../../../component/dependencyinjection/extension/extension#method_getConfiguration "Symfony\Component\DependencyInjection\Extension\Extension") | | | [processConfiguration](#method_processConfiguration)([ConfigurationInterface](../../../component/config/definition/configurationinterface "Symfony\Component\Config\Definition\ConfigurationInterface") $configuration, array $configs) | from [Extension](../../../component/dependencyinjection/extension/extension#method_processConfiguration "Symfony\Component\DependencyInjection\Extension\Extension") | | | [getProcessedConfigs](#method_getProcessedConfigs)() | from [Extension](../../../component/dependencyinjection/extension/extension#method_getProcessedConfigs "Symfony\Component\DependencyInjection\Extension\Extension") | | bool | [isConfigEnabled](#method_isConfigEnabled)([ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container, array $config) | from [Extension](../../../component/dependencyinjection/extension/extension#method_isConfigEnabled "Symfony\Component\DependencyInjection\Extension\Extension") | | array | [getAnnotatedClassesToCompile](#method_getAnnotatedClassesToCompile)() Gets the annotated classes to cache. | from [Extension](../../../component/httpkernel/dependencyinjection/extension#method_getAnnotatedClassesToCompile "Symfony\Component\HttpKernel\DependencyInjection\Extension") | | | [addAnnotatedClassesToCompile](#method_addAnnotatedClassesToCompile)(array $annotatedClasses) Adds annotated classes to the class cache. | from [Extension](../../../component/httpkernel/dependencyinjection/extension#method_addAnnotatedClassesToCompile "Symfony\Component\HttpKernel\DependencyInjection\Extension") | | | [loadMappingInformation](#method_loadMappingInformation)(array $objectManager, [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) | | | | [setMappingDriverAlias](#method_setMappingDriverAlias)(array $mappingConfig, string $mappingName) Register the alias for this mapping driver. | | | | [setMappingDriverConfig](#method_setMappingDriverConfig)(array $mappingConfig, string $mappingName) Register the mapping driver configuration for later use with the object managers metadata driver chain. | | | array|false | [getMappingDriverBundleConfigDefaults](#method_getMappingDriverBundleConfigDefaults)(array $bundleConfig, [ReflectionClass](http://php.net/ReflectionClass) $bundle, [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) If this is a bundle controlled mapping all the missing information can be autodetected by this method. | | | | [registerMappingDrivers](#method_registerMappingDrivers)(array $objectManager, [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Register all the collected mapping information with the object manager by registering the appropriate mapping drivers. | | | | [assertValidMappingConfiguration](#method_assertValidMappingConfiguration)(array $mappingConfig, string $objectManagerName) Assertion if the specified mapping information is valid. | | | string|null | [detectMetadataDriver](#method_detectMetadataDriver)(string $dir, [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Detects what metadata driver to use for the supplied directory. | | | | [loadObjectManagerCacheDriver](#method_loadObjectManagerCacheDriver)(array $objectManager, [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container, string $cacheName) Loads a configured object manager metadata, query or result cache driver. | | | string | [loadCacheDriver](#method_loadCacheDriver)(string $cacheName, string $objectManagerName, array $cacheDriver, [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Loads a cache driver. | | | array | [fixManagersAutoMappings](#method_fixManagersAutoMappings)(array $managerConfigs, array $bundles) Returns a modified version of $managerConfigs. | | | string | [getObjectManagerElementName](#method_getObjectManagerElementName)(string $name) Prefixes the relative dependency injection container path with the object manager prefix. | | | string | [getMappingObjectDefaultName](#method_getMappingObjectDefaultName)() Noun that describes the mapped objects such as Entity or Document. | | | string | [getMappingResourceConfigDirectory](#method_getMappingResourceConfigDirectory)() Relative path from the bundle root to the directory where mapping files reside. | | | string | [getMappingResourceExtension](#method_getMappingResourceExtension)() Extension used by the mapping files. | | Details ------- ### string getXsdValidationBasePath() Returns the base path for the XSD files. #### Return Value | | | | --- | --- | | string | The XSD base path | ### string getNamespace() Returns the namespace to be used for this extension (XML namespace). #### Return Value | | | | --- | --- | | string | The XML namespace | ### string getAlias() Returns the recommended alias to use in XML. This alias is also the mandatory prefix to use when using YAML. This convention is to remove the "Extension" postfix from the class name and then lowercase and underscore the result. So: ``` AcmeHelloExtension ``` becomes ``` acme_hello ``` This can be overridden in a sub-class to specify the alias manually. #### Return Value | | | | --- | --- | | string | The alias | #### Exceptions | | | | --- | --- | | [BadMethodCallException](../../../component/dependencyinjection/exception/badmethodcallexception "Symfony\Component\DependencyInjection\Exception\BadMethodCallException") | When the extension name does not follow conventions | ### [ConfigurationInterface](../../../component/config/definition/configurationinterface "Symfony\Component\Config\Definition\ConfigurationInterface")|null getConfiguration(array $config, [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Returns extension configuration. #### Parameters | | | | | --- | --- | --- | | array | $config | | | [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | #### Return Value | | | | --- | --- | | [ConfigurationInterface](../../../component/config/definition/configurationinterface "Symfony\Component\Config\Definition\ConfigurationInterface")|null | The configuration or null | ### final protected processConfiguration([ConfigurationInterface](../../../component/config/definition/configurationinterface "Symfony\Component\Config\Definition\ConfigurationInterface") $configuration, array $configs) #### Parameters | | | | | --- | --- | --- | | [ConfigurationInterface](../../../component/config/definition/configurationinterface "Symfony\Component\Config\Definition\ConfigurationInterface") | $configuration | | | array | $configs | | ### final getProcessedConfigs() ### protected bool isConfigEnabled([ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container, array $config) #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | | array | $config | | #### Return Value | | | | --- | --- | | bool | Whether the configuration is enabled | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](../../../component/dependencyinjection/exception/invalidargumentexception "Symfony\Component\DependencyInjection\Exception\InvalidArgumentException") | When the config is not enableable | ### array getAnnotatedClassesToCompile() Gets the annotated classes to cache. #### Return Value | | | | --- | --- | | array | An array of classes | ### addAnnotatedClassesToCompile(array $annotatedClasses) Adds annotated classes to the class cache. #### Parameters | | | | | --- | --- | --- | | array | $annotatedClasses | An array of class patterns | ### protected loadMappingInformation(array $objectManager, [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) #### Parameters | | | | | --- | --- | --- | | array | $objectManager | A configured object manager | | [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | A ContainerBuilder instance | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](http://php.net/InvalidArgumentException) | | ### protected setMappingDriverAlias(array $mappingConfig, string $mappingName) Register the alias for this mapping driver. Aliases can be used in the Query languages of all the Doctrine object managers to simplify writing tasks. #### Parameters | | | | | --- | --- | --- | | array | $mappingConfig | | | string | $mappingName | | ### protected setMappingDriverConfig(array $mappingConfig, string $mappingName) Register the mapping driver configuration for later use with the object managers metadata driver chain. #### Parameters | | | | | --- | --- | --- | | array | $mappingConfig | | | string | $mappingName | | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](http://php.net/InvalidArgumentException) | | ### protected array|false getMappingDriverBundleConfigDefaults(array $bundleConfig, [ReflectionClass](http://php.net/ReflectionClass) $bundle, [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) If this is a bundle controlled mapping all the missing information can be autodetected by this method. Returns false when autodetection failed, an array of the completed information otherwise. #### Parameters | | | | | --- | --- | --- | | array | $bundleConfig | | | [ReflectionClass](http://php.net/ReflectionClass) | $bundle | | | [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | #### Return Value | | | | --- | --- | | array|false | | ### protected registerMappingDrivers(array $objectManager, [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Register all the collected mapping information with the object manager by registering the appropriate mapping drivers. #### Parameters | | | | | --- | --- | --- | | array | $objectManager | | | [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | A ContainerBuilder instance | ### protected assertValidMappingConfiguration(array $mappingConfig, string $objectManagerName) Assertion if the specified mapping information is valid. #### Parameters | | | | | --- | --- | --- | | array | $mappingConfig | | | string | $objectManagerName | | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](http://php.net/InvalidArgumentException) | | ### protected string|null detectMetadataDriver(string $dir, [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Detects what metadata driver to use for the supplied directory. #### Parameters | | | | | --- | --- | --- | | string | $dir | A directory path | | [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | A ContainerBuilder instance | #### Return Value | | | | --- | --- | | string|null | A metadata driver short name, if one can be detected | ### protected loadObjectManagerCacheDriver(array $objectManager, [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container, string $cacheName) Loads a configured object manager metadata, query or result cache driver. #### Parameters | | | | | --- | --- | --- | | array | $objectManager | A configured object manager | | [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | A ContainerBuilder instance | | string | $cacheName | | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](http://php.net/InvalidArgumentException) | in case of unknown driver type | ### protected string loadCacheDriver(string $cacheName, string $objectManagerName, array $cacheDriver, [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Loads a cache driver. #### Parameters | | | | | --- | --- | --- | | string | $cacheName | The cache driver name | | string | $objectManagerName | The object manager name | | array | $cacheDriver | The cache driver mapping | | [ContainerBuilder](../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | The ContainerBuilder instance | #### Return Value | | | | --- | --- | | string | | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](http://php.net/InvalidArgumentException) | | ### protected array fixManagersAutoMappings(array $managerConfigs, array $bundles) Returns a modified version of $managerConfigs. The manager called $autoMappedManager will map all bundles that are not mapped by other managers. #### Parameters | | | | | --- | --- | --- | | array | $managerConfigs | | | array | $bundles | | #### Return Value | | | | --- | --- | | array | The modified version of $managerConfigs | ### abstract protected string getObjectManagerElementName(string $name) Prefixes the relative dependency injection container path with the object manager prefix. #### Parameters | | | | | --- | --- | --- | | string | $name | | #### Return Value | | | | --- | --- | | string | | ### abstract protected string getMappingObjectDefaultName() Noun that describes the mapped objects such as Entity or Document. Will be used for autodetection of persistent objects directory. #### Return Value | | | | --- | --- | | string | | ### abstract protected string getMappingResourceConfigDirectory() Relative path from the bundle root to the directory where mapping files reside. #### Return Value | | | | --- | --- | | string | | ### abstract protected string getMappingResourceExtension() Extension used by the mapping files. #### Return Value | | | | --- | --- | | string | |
programming_docs
symfony Symfony\Bridge\Doctrine\DependencyInjection\Security\UserProvider Symfony\Bridge\Doctrine\DependencyInjection\Security\UserProvider ================================================================= Classes ------- | | | | --- | --- | | [EntityFactory](userprovider/entityfactory "Symfony\Bridge\Doctrine\DependencyInjection\Security\UserProvider\EntityFactory") | EntityFactory creates services for Doctrine user provider. | symfony EntityFactory EntityFactory ============== class **EntityFactory** implements [UserProviderFactoryInterface](../../../../../bundle/securitybundle/dependencyinjection/security/userprovider/userproviderfactoryinterface "Symfony\Bundle\SecurityBundle\DependencyInjection\Security\UserProvider\UserProviderFactoryInterface") EntityFactory creates services for Doctrine user provider. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $key, string $providerId) | | | | [create](#method_create)([ContainerBuilder](../../../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container, $id, $config) | | | | [getKey](#method_getKey)() | | | | [addConfiguration](#method_addConfiguration)([NodeDefinition](../../../../../component/config/definition/builder/nodedefinition "Symfony\Component\Config\Definition\Builder\NodeDefinition") $node) | | Details ------- ### \_\_construct(string $key, string $providerId) #### Parameters | | | | | --- | --- | --- | | string | $key | | | string | $providerId | | ### create([ContainerBuilder](../../../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container, $id, $config) #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../../../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | | | $id | | | | $config | | ### getKey() ### addConfiguration([NodeDefinition](../../../../../component/config/definition/builder/nodedefinition "Symfony\Component\Config\Definition\Builder\NodeDefinition") $node) #### Parameters | | | | | --- | --- | --- | | [NodeDefinition](../../../../../component/config/definition/builder/nodedefinition "Symfony\Component\Config\Definition\Builder\NodeDefinition") | $node | | symfony DoctrineValidationPass DoctrineValidationPass ======================= class **DoctrineValidationPass** implements [CompilerPassInterface](../../../../component/dependencyinjection/compiler/compilerpassinterface "Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface") Registers additional validators. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $managerType) | | | | [process](#method_process)([ContainerBuilder](../../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) You can modify the container here before it is dumped to PHP code. | | Details ------- ### \_\_construct(string $managerType) #### Parameters | | | | | --- | --- | --- | | string | $managerType | | ### process([ContainerBuilder](../../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) You can modify the container here before it is dumped to PHP code. #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | symfony RegisterMappingsPass RegisterMappingsPass ===================== abstract class **RegisterMappingsPass** implements [CompilerPassInterface](../../../../component/dependencyinjection/compiler/compilerpassinterface "Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface") Base class for the doctrine bundles to provide a compiler pass class that helps to register doctrine mappings. The compiler pass is meant to register the mappings with the metadata chain driver corresponding to one of the object managers. For concrete implementations that are easy to use, see the RegisterXyMappingsPass classes in the DoctrineBundle resp. DoctrineMongodbBundle, DoctrineCouchdbBundle and DoctrinePhpcrBundle. Properties ---------- | | | | | | --- | --- | --- | --- | | protected [Definition](../../../../component/dependencyinjection/definition "Symfony\Component\DependencyInjection\Definition")|[Reference](../../../../component/dependencyinjection/reference "Symfony\Component\DependencyInjection\Reference") | $driver | DI object for the driver to use, either a service definition for a private service or a reference for a public service. | | | protected string[] | $namespaces | List of namespaces handled by the driver. | | | protected string[] | $managerParameters | List of potential container parameters that hold the object manager name to register the mappings with the correct metadata driver, for example array('acme.manager', 'doctrine.default\_entity\_manager'). | | | protected string | $driverPattern | Naming pattern of the metadata chain driver service ids, for example 'doctrine.orm.%s\_metadata\_driver'. | | | protected string|false | $enabledParameter | A name for a parameter in the container. If set, this compiler pass will only do anything if the parameter is present. (But regardless of the value of that parameter. | | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([Definition](../../../../component/dependencyinjection/definition "Symfony\Component\DependencyInjection\Definition")|[Reference](../../../../component/dependencyinjection/reference "Symfony\Component\DependencyInjection\Reference") $driver, array $namespaces, array $managerParameters, string $driverPattern, string|false $enabledParameter = false, string $configurationPattern = '', string $registerAliasMethodName = '', array $aliasMap = array()) The $managerParameters is an ordered list of container parameters that could provide the name of the manager to register these namespaces and alias on. The first non-empty name is used, the others skipped. | | | | [process](#method_process)([ContainerBuilder](../../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Register mappings and alias with the metadata drivers. | | | string | [getChainDriverServiceName](#method_getChainDriverServiceName)([ContainerBuilder](../../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Get the service name of the metadata chain driver that the mappings should be registered with. | | | [Definition](../../../../component/dependencyinjection/definition "Symfony\Component\DependencyInjection\Definition")|[Reference](../../../../component/dependencyinjection/reference "Symfony\Component\DependencyInjection\Reference") | [getDriver](#method_getDriver)([ContainerBuilder](../../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Create the service definition for the metadata driver. | | | bool | [enabled](#method_enabled)([ContainerBuilder](../../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Determine whether this mapping should be activated or not. This allows to take this decision with the container builder available. | | Details ------- ### \_\_construct([Definition](../../../../component/dependencyinjection/definition "Symfony\Component\DependencyInjection\Definition")|[Reference](../../../../component/dependencyinjection/reference "Symfony\Component\DependencyInjection\Reference") $driver, array $namespaces, array $managerParameters, string $driverPattern, string|false $enabledParameter = false, string $configurationPattern = '', string $registerAliasMethodName = '', array $aliasMap = array()) The $managerParameters is an ordered list of container parameters that could provide the name of the manager to register these namespaces and alias on. The first non-empty name is used, the others skipped. The $aliasMap parameter can be used to define bundle namespace shortcuts like the DoctrineBundle provides automatically for objects in the default Entity/Document folder. #### Parameters | | | | | --- | --- | --- | | [Definition](../../../../component/dependencyinjection/definition "Symfony\Component\DependencyInjection\Definition")|[Reference](../../../../component/dependencyinjection/reference "Symfony\Component\DependencyInjection\Reference") | $driver | Driver DI definition or reference | | array | $namespaces | List of namespaces handled by $driver | | array | $managerParameters | list of container parameters that could hold the manager name | | string | $driverPattern | Pattern for the metadata driver service name | | string|false | $enabledParameter | Service container parameter that must be present to enable the mapping. Set to false to not do any check, optional. | | string | $configurationPattern | Pattern for the Configuration service name | | string | $registerAliasMethodName | Name of Configuration class method to register alias | | array | $aliasMap | Map of alias to namespace | ### process([ContainerBuilder](../../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Register mappings and alias with the metadata drivers. #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | ### protected string getChainDriverServiceName([ContainerBuilder](../../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Get the service name of the metadata chain driver that the mappings should be registered with. #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | #### Return Value | | | | --- | --- | | string | The name of the chain driver service | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](../../../../component/dependencyinjection/exception/invalidargumentexception "Symfony\Component\DependencyInjection\Exception\InvalidArgumentException") | if non of the managerParameters has a non-empty value | ### protected [Definition](../../../../component/dependencyinjection/definition "Symfony\Component\DependencyInjection\Definition")|[Reference](../../../../component/dependencyinjection/reference "Symfony\Component\DependencyInjection\Reference") getDriver([ContainerBuilder](../../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Create the service definition for the metadata driver. #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | Passed on in case an extending class needs access to the container | #### Return Value | | | | --- | --- | | [Definition](../../../../component/dependencyinjection/definition "Symfony\Component\DependencyInjection\Definition")|[Reference](../../../../component/dependencyinjection/reference "Symfony\Component\DependencyInjection\Reference") | the metadata driver to add to all chain drivers | ### protected bool enabled([ContainerBuilder](../../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Determine whether this mapping should be activated or not. This allows to take this decision with the container builder available. This default implementation checks if the class has the enabledParameter configured and if so if that parameter is present in the container. #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | #### Return Value | | | | --- | --- | | bool | whether this compiler pass really should register the mappings | symfony RegisterEventListenersAndSubscribersPass RegisterEventListenersAndSubscribersPass ========================================= class **RegisterEventListenersAndSubscribersPass** implements [CompilerPassInterface](../../../../component/dependencyinjection/compiler/compilerpassinterface "Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface") Registers event listeners and subscribers to the available doctrine connections. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $connections, string $managerTemplate, string $tagPrefix) | | | | [process](#method_process)([ContainerBuilder](../../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) You can modify the container here before it is dumped to PHP code. | | Details ------- ### \_\_construct(string $connections, string $managerTemplate, string $tagPrefix) #### Parameters | | | | | --- | --- | --- | | string | $connections | Parameter ID for connections | | string | $managerTemplate | sprintf() template for generating the event manager's service ID for a connection name | | string | $tagPrefix | Tag prefix for listeners and subscribers | ### process([ContainerBuilder](../../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) You can modify the container here before it is dumped to PHP code. #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../../../../component/dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | symfony DnsMock DnsMock ======== class **DnsMock** Methods ------- | | | | | --- | --- | --- | | static | [withMockedHosts](#method_withMockedHosts)(array $hosts) Configures the mock values for DNS queries. | | | static | [checkdnsrr](#method_checkdnsrr)($hostname, $type = 'MX') | | | static | [getmxrr](#method_getmxrr)($hostname, $mxhosts, $weight = null) | | | static | [gethostbyaddr](#method_gethostbyaddr)($ipAddress) | | | static | [gethostbyname](#method_gethostbyname)($hostname) | | | static | [gethostbynamel](#method_gethostbynamel)($hostname) | | | static | [dns\_get\_record](#method_dns_get_record)($hostname, $type = DNS\_ANY, $authns = null, $addtl = null, $raw = false) | | | static | [register](#method_register)($class) | | Details ------- ### static withMockedHosts(array $hosts) Configures the mock values for DNS queries. #### Parameters | | | | | --- | --- | --- | | array | $hosts | Mocked hosts as keys, arrays of DNS records as returned by dns\_get\_record() as values | ### static checkdnsrr($hostname, $type = 'MX') #### Parameters | | | | | --- | --- | --- | | | $hostname | | | | $type | | ### static getmxrr($hostname, $mxhosts, $weight = null) #### Parameters | | | | | --- | --- | --- | | | $hostname | | | | $mxhosts | | | | $weight | | ### static gethostbyaddr($ipAddress) #### Parameters | | | | | --- | --- | --- | | | $ipAddress | | ### static gethostbyname($hostname) #### Parameters | | | | | --- | --- | --- | | | $hostname | | ### static gethostbynamel($hostname) #### Parameters | | | | | --- | --- | --- | | | $hostname | | ### static dns\_get\_record($hostname, $type = DNS\_ANY, $authns = null, $addtl = null, $raw = false) #### Parameters | | | | | --- | --- | --- | | | $hostname | | | | $type | | | | $authns | | | | $addtl | | | | $raw | | ### static register($class) #### Parameters | | | | | --- | --- | --- | | | $class | | symfony DeprecationErrorHandler DeprecationErrorHandler ======================== class **DeprecationErrorHandler** Catch deprecation notices and print a summary report at the end of the test suite. Constants --------- | | | | --- | --- | | MODE\_WEAK | | | MODE\_WEAK\_VENDORS | | | MODE\_DISABLED | | Methods ------- | | | | | --- | --- | --- | | static | [register](#method_register)(int|string|false $mode = 0) Registers and configures the deprecation handler. | | | static | [collectDeprecations](#method_collectDeprecations)($outputFile) | | Details ------- ### static register(int|string|false $mode = 0) Registers and configures the deprecation handler. The following reporting modes are supported: - use "weak" to hide the deprecation report but keep a global count; - use "weak\_vendors" to fail only on deprecations triggered in your own code; - use "/some-regexp/" to stop the test suite whenever a deprecation message matches the given regular expression; - use a number to define the upper bound of allowed deprecations, making the test suite fail whenever more notices are trigerred. #### Parameters | | | | | --- | --- | --- | | int|string|false | $mode | The reporting mode, defaults to not allowing any deprecations | ### static collectDeprecations($outputFile) #### Parameters | | | | | --- | --- | --- | | | $outputFile | | symfony Symfony\Bridge\PhpUnit\Legacy Symfony\Bridge\PhpUnit\Legacy ============================= Classes ------- | | | | --- | --- | | [CommandForV5](legacy/commandforv5 "Symfony\Bridge\PhpUnit\Legacy\CommandForV5") | {@inheritdoc} | | [CommandForV6](legacy/commandforv6 "Symfony\Bridge\PhpUnit\Legacy\CommandForV6") | {@inheritdoc} | | [CoverageListenerForV5](legacy/coveragelistenerforv5 "Symfony\Bridge\PhpUnit\Legacy\CoverageListenerForV5") | CoverageListener adds `@covers <className>` on each test when possible to make the code coverage more accurate. | | [CoverageListenerForV6](legacy/coveragelistenerforv6 "Symfony\Bridge\PhpUnit\Legacy\CoverageListenerForV6") | CoverageListener adds `@covers <className>` on each test when possible to make the code coverage more accurate. | | [CoverageListenerForV7](legacy/coveragelistenerforv7 "Symfony\Bridge\PhpUnit\Legacy\CoverageListenerForV7") | CoverageListener adds `@covers <className>` on each test when possible to make the code coverage more accurate. | | [CoverageListenerTrait](legacy/coveragelistenertrait "Symfony\Bridge\PhpUnit\Legacy\CoverageListenerTrait") | PHP 5.3 compatible trait-like shared implementation. | | [SymfonyTestsListenerForV5](legacy/symfonytestslistenerforv5 "Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerForV5") | Collects and replays skipped tests. | | [SymfonyTestsListenerForV6](legacy/symfonytestslistenerforv6 "Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerForV6") | Collects and replays skipped tests. | | [SymfonyTestsListenerForV7](legacy/symfonytestslistenerforv7 "Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerForV7") | Collects and replays skipped tests. | | [SymfonyTestsListenerTrait](legacy/symfonytestslistenertrait "Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerTrait") | PHP 5.3 compatible trait-like shared implementation. | | [TestRunnerForV5](legacy/testrunnerforv5 "Symfony\Bridge\PhpUnit\Legacy\TestRunnerForV5") | {@inheritdoc} | | [TestRunnerForV6](legacy/testrunnerforv6 "Symfony\Bridge\PhpUnit\Legacy\TestRunnerForV6") | {@inheritdoc} | | [TestRunnerForV7](legacy/testrunnerforv7 "Symfony\Bridge\PhpUnit\Legacy\TestRunnerForV7") | {@inheritdoc} |
programming_docs
symfony ClockMock ClockMock ========== class **ClockMock** Methods ------- | | | | | --- | --- | --- | | static | [withClockMock](#method_withClockMock)($enable = null) | | | static | [time](#method_time)() | | | static | [sleep](#method_sleep)($s) | | | static | [usleep](#method_usleep)($us) | | | static | [microtime](#method_microtime)($asFloat = false) | | | static | [register](#method_register)($class) | | Details ------- ### static withClockMock($enable = null) #### Parameters | | | | | --- | --- | --- | | | $enable | | ### static time() ### static sleep($s) #### Parameters | | | | | --- | --- | --- | | | $s | | ### static usleep($us) #### Parameters | | | | | --- | --- | --- | | | $us | | ### static microtime($asFloat = false) #### Parameters | | | | | --- | --- | --- | | | $asFloat | | ### static register($class) #### Parameters | | | | | --- | --- | --- | | | $class | | symfony Symfony\Bridge\PhpUnit\TextUI Symfony\Bridge\PhpUnit\TextUI ============================= Classes ------- | | | | --- | --- | | [Command](textui/command "Symfony\Bridge\PhpUnit\TextUI\Command") | | | [TestRunner](textui/testrunner "Symfony\Bridge\PhpUnit\TextUI\TestRunner") | | symfony TestRunnerForV6 TestRunnerForV6 ================ class **TestRunnerForV6** extends TestRunner {@inheritdoc} Methods ------- | | | | | --- | --- | --- | | | [handleConfiguration](#method_handleConfiguration)(array $arguments) {@inheritdoc} | | Details ------- ### protected handleConfiguration(array $arguments) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | array | $arguments | | symfony CoverageListenerForV7 CoverageListenerForV7 ====================== class **CoverageListenerForV7** implements TestListener CoverageListener adds `@covers <className>` on each test when possible to make the code coverage more accurate. Traits ------ | | | | --- | --- | | TestListenerDefaultImplementation | | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(callable $sutFqcnResolver = null, $warningOnSutNotFound = false) | | | void | [startTest](#method_startTest)(Test $test) | | Details ------- ### \_\_construct(callable $sutFqcnResolver = null, $warningOnSutNotFound = false) #### Parameters | | | | | --- | --- | --- | | callable | $sutFqcnResolver | | | | $warningOnSutNotFound | | ### void startTest(Test $test) #### Parameters | | | | | --- | --- | --- | | Test | $test | | #### Return Value | | | | --- | --- | | void | | symfony SymfonyTestsListenerForV6 SymfonyTestsListenerForV6 ========================== class **SymfonyTestsListenerForV6** extends BaseTestListener Collects and replays skipped tests. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(array $mockedNamespaces = array()) | | | | [globalListenerDisabled](#method_globalListenerDisabled)() | | | | [startTestSuite](#method_startTestSuite)(TestSuite $suite) | | | | [addSkippedTest](#method_addSkippedTest)(Test $test, [Exception](http://php.net/Exception) $e, $time) | | | | [startTest](#method_startTest)(Test $test) | | | | [addWarning](#method_addWarning)(Test $test, Warning $e, $time) | | | | [endTest](#method_endTest)(Test $test, $time) | | Details ------- ### \_\_construct(array $mockedNamespaces = array()) #### Parameters | | | | | --- | --- | --- | | array | $mockedNamespaces | | ### globalListenerDisabled() ### startTestSuite(TestSuite $suite) #### Parameters | | | | | --- | --- | --- | | TestSuite | $suite | | ### addSkippedTest(Test $test, [Exception](http://php.net/Exception) $e, $time) #### Parameters | | | | | --- | --- | --- | | Test | $test | | | [Exception](http://php.net/Exception) | $e | | | | $time | | ### startTest(Test $test) #### Parameters | | | | | --- | --- | --- | | Test | $test | | ### addWarning(Test $test, Warning $e, $time) #### Parameters | | | | | --- | --- | --- | | Test | $test | | | Warning | $e | | | | $time | | ### endTest(Test $test, $time) #### Parameters | | | | | --- | --- | --- | | Test | $test | | | | $time | | symfony SymfonyTestsListenerForV7 SymfonyTestsListenerForV7 ========================== class **SymfonyTestsListenerForV7** implements TestListener Collects and replays skipped tests. Traits ------ | | | | --- | --- | | TestListenerDefaultImplementation | | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(array $mockedNamespaces = array()) | | | | [globalListenerDisabled](#method_globalListenerDisabled)() | | | void | [startTestSuite](#method_startTestSuite)(TestSuite $suite) | | | void | [addSkippedTest](#method_addSkippedTest)(Test $test, [Throwable](http://php.net/Throwable) $t, float $time) | | | void | [startTest](#method_startTest)(Test $test) | | | void | [addWarning](#method_addWarning)(Test $test, Warning $e, float $time) | | | void | [endTest](#method_endTest)(Test $test, float $time) | | Details ------- ### \_\_construct(array $mockedNamespaces = array()) #### Parameters | | | | | --- | --- | --- | | array | $mockedNamespaces | | ### globalListenerDisabled() ### void startTestSuite(TestSuite $suite) #### Parameters | | | | | --- | --- | --- | | TestSuite | $suite | | #### Return Value | | | | --- | --- | | void | | ### void addSkippedTest(Test $test, [Throwable](http://php.net/Throwable) $t, float $time) #### Parameters | | | | | --- | --- | --- | | Test | $test | | | [Throwable](http://php.net/Throwable) | $t | | | float | $time | | #### Return Value | | | | --- | --- | | void | | ### void startTest(Test $test) #### Parameters | | | | | --- | --- | --- | | Test | $test | | #### Return Value | | | | --- | --- | | void | | ### void addWarning(Test $test, Warning $e, float $time) #### Parameters | | | | | --- | --- | --- | | Test | $test | | | Warning | $e | | | float | $time | | #### Return Value | | | | --- | --- | | void | | ### void endTest(Test $test, float $time) #### Parameters | | | | | --- | --- | --- | | Test | $test | | | float | $time | | #### Return Value | | | | --- | --- | | void | | symfony CoverageListenerForV6 CoverageListenerForV6 ====================== class **CoverageListenerForV6** extends BaseTestListener CoverageListener adds `@covers <className>` on each test when possible to make the code coverage more accurate. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(callable $sutFqcnResolver = null, $warningOnSutNotFound = false) | | | | [startTest](#method_startTest)(Test $test) | | Details ------- ### \_\_construct(callable $sutFqcnResolver = null, $warningOnSutNotFound = false) #### Parameters | | | | | --- | --- | --- | | callable | $sutFqcnResolver | | | | $warningOnSutNotFound | | ### startTest(Test $test) #### Parameters | | | | | --- | --- | --- | | Test | $test | | symfony TestRunnerForV7 TestRunnerForV7 ================ class **TestRunnerForV7** extends TestRunner {@inheritdoc} Methods ------- | | | | | --- | --- | --- | | void | [handleConfiguration](#method_handleConfiguration)(array $arguments) {@inheritdoc} | | Details ------- ### protected void handleConfiguration(array $arguments) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | array | $arguments | | #### Return Value | | | | --- | --- | | void | | symfony CommandForV5 CommandForV5 ============= class **CommandForV5** extends PHPUnit\_TextUI\_Command {@inheritdoc} Methods ------- | | | | | --- | --- | --- | | | [createRunner](#method_createRunner)() {@inheritdoc} | | Details ------- ### protected createRunner() {@inheritdoc} symfony SymfonyTestsListenerTrait SymfonyTestsListenerTrait ========================== class **SymfonyTestsListenerTrait** PHP 5.3 compatible trait-like shared implementation. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(array $mockedNamespaces = array()) | | | | [\_\_destruct](#method___destruct)() | | | | [globalListenerDisabled](#method_globalListenerDisabled)() | | | | [startTestSuite](#method_startTestSuite)($suite) | | | | [addSkippedTest](#method_addSkippedTest)($test, [Exception](http://php.net/Exception) $e, $time) | | | | [startTest](#method_startTest)($test) | | | | [addWarning](#method_addWarning)($test, $e, $time) | | | | [endTest](#method_endTest)($test, $time) | | | | [handleError](#method_handleError)($type, $msg, $file, $line, $context = array()) | | Details ------- ### \_\_construct(array $mockedNamespaces = array()) #### Parameters | | | | | --- | --- | --- | | array | $mockedNamespaces | List of namespaces, indexed by mocked features (time-sensitive or dns-sensitive) | ### \_\_destruct() ### globalListenerDisabled() ### startTestSuite($suite) #### Parameters | | | | | --- | --- | --- | | | $suite | | ### addSkippedTest($test, [Exception](http://php.net/Exception) $e, $time) #### Parameters | | | | | --- | --- | --- | | | $test | | | [Exception](http://php.net/Exception) | $e | | | | $time | | ### startTest($test) #### Parameters | | | | | --- | --- | --- | | | $test | | ### addWarning($test, $e, $time) #### Parameters | | | | | --- | --- | --- | | | $test | | | | $e | | | | $time | | ### endTest($test, $time) #### Parameters | | | | | --- | --- | --- | | | $test | | | | $time | | ### handleError($type, $msg, $file, $line, $context = array()) #### Parameters | | | | | --- | --- | --- | | | $type | | | | $msg | | | | $file | | | | $line | | | | $context | | symfony CommandForV6 CommandForV6 ============= class **CommandForV6** extends Command {@inheritdoc} Methods ------- | | | | | --- | --- | --- | | TestRunner | [createRunner](#method_createRunner)() {@inheritdoc} | | Details ------- ### protected TestRunner createRunner() {@inheritdoc} #### Return Value | | | | --- | --- | | TestRunner | | symfony CoverageListenerTrait CoverageListenerTrait ====================== class **CoverageListenerTrait** PHP 5.3 compatible trait-like shared implementation. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(callable $sutFqcnResolver = null, $warningOnSutNotFound = false) | | | | [startTest](#method_startTest)($test) | | | | [\_\_destruct](#method___destruct)() | | Details ------- ### \_\_construct(callable $sutFqcnResolver = null, $warningOnSutNotFound = false) #### Parameters | | | | | --- | --- | --- | | callable | $sutFqcnResolver | | | | $warningOnSutNotFound | | ### startTest($test) #### Parameters | | | | | --- | --- | --- | | | $test | | ### \_\_destruct() symfony CoverageListenerForV5 CoverageListenerForV5 ====================== class **CoverageListenerForV5** extends PHPUnit\_Framework\_BaseTestListener CoverageListener adds `@covers <className>` on each test when possible to make the code coverage more accurate. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(callable $sutFqcnResolver = null, $warningOnSutNotFound = false) | | | | [startTest](#method_startTest)(PHPUnit\_Framework\_Test $test) | | Details ------- ### \_\_construct(callable $sutFqcnResolver = null, $warningOnSutNotFound = false) #### Parameters | | | | | --- | --- | --- | | callable | $sutFqcnResolver | | | | $warningOnSutNotFound | | ### startTest(PHPUnit\_Framework\_Test $test) #### Parameters | | | | | --- | --- | --- | | PHPUnit\_Framework\_Test | $test | | symfony SymfonyTestsListenerForV5 SymfonyTestsListenerForV5 ========================== class **SymfonyTestsListenerForV5** extends PHPUnit\_Framework\_BaseTestListener Collects and replays skipped tests. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(array $mockedNamespaces = array()) | | | | [globalListenerDisabled](#method_globalListenerDisabled)() | | | | [startTestSuite](#method_startTestSuite)(PHPUnit\_Framework\_TestSuite $suite) | | | | [addSkippedTest](#method_addSkippedTest)(PHPUnit\_Framework\_Test $test, [Exception](http://php.net/Exception) $e, $time) | | | | [startTest](#method_startTest)(PHPUnit\_Framework\_Test $test) | | | | [addWarning](#method_addWarning)(PHPUnit\_Framework\_Test $test, PHPUnit\_Framework\_Warning $e, $time) | | | | [endTest](#method_endTest)(PHPUnit\_Framework\_Test $test, $time) | | Details ------- ### \_\_construct(array $mockedNamespaces = array()) #### Parameters | | | | | --- | --- | --- | | array | $mockedNamespaces | | ### globalListenerDisabled() ### startTestSuite(PHPUnit\_Framework\_TestSuite $suite) #### Parameters | | | | | --- | --- | --- | | PHPUnit\_Framework\_TestSuite | $suite | | ### addSkippedTest(PHPUnit\_Framework\_Test $test, [Exception](http://php.net/Exception) $e, $time) #### Parameters | | | | | --- | --- | --- | | PHPUnit\_Framework\_Test | $test | | | [Exception](http://php.net/Exception) | $e | | | | $time | | ### startTest(PHPUnit\_Framework\_Test $test) #### Parameters | | | | | --- | --- | --- | | PHPUnit\_Framework\_Test | $test | | ### addWarning(PHPUnit\_Framework\_Test $test, PHPUnit\_Framework\_Warning $e, $time) #### Parameters | | | | | --- | --- | --- | | PHPUnit\_Framework\_Test | $test | | | PHPUnit\_Framework\_Warning | $e | | | | $time | | ### endTest(PHPUnit\_Framework\_Test $test, $time) #### Parameters | | | | | --- | --- | --- | | PHPUnit\_Framework\_Test | $test | | | | $time | | symfony TestRunnerForV5 TestRunnerForV5 ================ class **TestRunnerForV5** extends PHPUnit\_TextUI\_TestRunner {@inheritdoc} Methods ------- | | | | | --- | --- | --- | | | [handleConfiguration](#method_handleConfiguration)(array $arguments) {@inheritdoc} | | Details ------- ### protected handleConfiguration(array $arguments) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | array | $arguments | | symfony Symfony\Bridge\Monolog\Handler Symfony\Bridge\Monolog\Handler ============================== Namespaces ---------- [Symfony\Bridge\Monolog\Handler\FingersCrossed](handler/fingerscrossed) Classes ------- | | | | --- | --- | | [ChromePhpHandler](handler/chromephphandler "Symfony\Bridge\Monolog\Handler\ChromePhpHandler") | ChromePhpHandler. | | [ConsoleHandler](handler/consolehandler "Symfony\Bridge\Monolog\Handler\ConsoleHandler") | Writes logs to the console output depending on its verbosity setting. | | [FirePHPHandler](handler/firephphandler "Symfony\Bridge\Monolog\Handler\FirePHPHandler") | FirePHPHandler. | | [ServerLogHandler](handler/serverloghandler "Symfony\Bridge\Monolog\Handler\ServerLogHandler") | | | [SwiftMailerHandler](handler/swiftmailerhandler "Symfony\Bridge\Monolog\Handler\SwiftMailerHandler") | Extended SwiftMailerHandler that flushes mail queue if necessary. | symfony Logger Logger ======= class **Logger** extends Logger implements [DebugLoggerInterface](../../component/httpkernel/log/debugloggerinterface "Symfony\Component\HttpKernel\Log\DebugLoggerInterface") Logger. Methods ------- | | | | | --- | --- | --- | | array | [getLogs](#method_getLogs)() Returns an array of logs. | | | int | [countErrors](#method_countErrors)() Returns the number of errors. | | | | [clear](#method_clear)() Removes all log records. | | Details ------- ### array getLogs() Returns an array of logs. A log is an array with the following mandatory keys: timestamp, message, priority, and priorityName. It can also have an optional context key containing an array. #### Return Value | | | | --- | --- | | array | An array of logs | ### int countErrors() Returns the number of errors. #### Return Value | | | | --- | --- | | int | The number of errors | ### clear() Removes all log records. symfony Symfony\Bridge\Monolog\Processor Symfony\Bridge\Monolog\Processor ================================ Classes ------- | | | | --- | --- | | [DebugProcessor](processor/debugprocessor "Symfony\Bridge\Monolog\Processor\DebugProcessor") | | | [TokenProcessor](processor/tokenprocessor "Symfony\Bridge\Monolog\Processor\TokenProcessor") | Adds the current security token to the log entry. | | [WebProcessor](processor/webprocessor "Symfony\Bridge\Monolog\Processor\WebProcessor") | WebProcessor override to read from the HttpFoundation's Request. | symfony Symfony\Bridge\Monolog\Formatter Symfony\Bridge\Monolog\Formatter ================================ Classes ------- | | | | --- | --- | | [ConsoleFormatter](formatter/consoleformatter "Symfony\Bridge\Monolog\Formatter\ConsoleFormatter") | Formats incoming records for console output by coloring them depending on log level. | | [VarDumperFormatter](formatter/vardumperformatter "Symfony\Bridge\Monolog\Formatter\VarDumperFormatter") | | symfony Symfony\Bridge\Monolog\Handler\FingersCrossed Symfony\Bridge\Monolog\Handler\FingersCrossed ============================================= Classes ------- | | | | --- | --- | | [HttpCodeActivationStrategy](fingerscrossed/httpcodeactivationstrategy "Symfony\Bridge\Monolog\Handler\FingersCrossed\HttpCodeActivationStrategy") | Activation strategy that ignores certain HTTP codes. | | [NotFoundActivationStrategy](fingerscrossed/notfoundactivationstrategy "Symfony\Bridge\Monolog\Handler\FingersCrossed\NotFoundActivationStrategy") | Activation strategy that ignores 404s for certain URLs. | symfony FirePHPHandler FirePHPHandler =============== class **FirePHPHandler** extends FirePHPHandler FirePHPHandler. Methods ------- | | | | | --- | --- | --- | | | [onKernelResponse](#method_onKernelResponse)([FilterResponseEvent](../../../component/httpkernel/event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) Adds the headers to the response once it's created. | | | | [sendHeader](#method_sendHeader)($header, $content) {@inheritdoc} | | | | [headersAccepted](#method_headersAccepted)() Override default behavior since we check the user agent in onKernelResponse. | | Details ------- ### onKernelResponse([FilterResponseEvent](../../../component/httpkernel/event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) Adds the headers to the response once it's created. #### Parameters | | | | | --- | --- | --- | | [FilterResponseEvent](../../../component/httpkernel/event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") | $event | | ### protected sendHeader($header, $content) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | | $header | | | | $content | | ### protected headersAccepted() Override default behavior since we check the user agent in onKernelResponse. symfony ServerLogHandler ServerLogHandler ================= class **ServerLogHandler** extends AbstractHandler Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $host, int $level = Logger::DEBUG, bool $bubble = true, array $context = array()) | | | | [handle](#method_handle)(array $record) {@inheritdoc} | | | | [getDefaultFormatter](#method_getDefaultFormatter)() {@inheritdoc} | | Details ------- ### \_\_construct(string $host, int $level = Logger::DEBUG, bool $bubble = true, array $context = array()) #### Parameters | | | | | --- | --- | --- | | string | $host | | | int | $level | | | bool | $bubble | | | array | $context | | ### handle(array $record) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | array | $record | | ### protected getDefaultFormatter() {@inheritdoc}
programming_docs
symfony ConsoleHandler ConsoleHandler =============== class **ConsoleHandler** extends AbstractProcessingHandler implements [EventSubscriberInterface](../../../component/eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") Writes logs to the console output depending on its verbosity setting. It is disabled by default and gets activated as soon as a command is executed. Instead of listening to the console events, the output can also be set manually. The minimum logging level at which this handler will be triggered depends on the verbosity setting of the console output. The default mapping is: - OutputInterface::VERBOSITY\_NORMAL will show all WARNING and higher logs - OutputInterface::VERBOSITY\_VERBOSE (-v) will show all NOTICE and higher logs - OutputInterface::VERBOSITY\_VERY\_VERBOSE (-vv) will show all INFO and higher logs - OutputInterface::VERBOSITY\_DEBUG (-vvv) will show all DEBUG and higher logs, i.e. all logs This mapping can be customized with the $verbosityLevelMap constructor parameter. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") $output = null, bool $bubble = true, array $verbosityLevelMap = array()) | | | | [isHandling](#method_isHandling)(array $record) {@inheritdoc} | | | | [handle](#method_handle)(array $record) {@inheritdoc} | | | | [setOutput](#method_setOutput)([OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") $output) Sets the console output to use for printing logs. | | | | [close](#method_close)() Disables the output. | | | | [onCommand](#method_onCommand)([ConsoleCommandEvent](../../../component/console/event/consolecommandevent "Symfony\Component\Console\Event\ConsoleCommandEvent") $event) Before a command is executed, the handler gets activated and the console output is set in order to know where to write the logs. | | | | [onTerminate](#method_onTerminate)([ConsoleTerminateEvent](../../../component/console/event/consoleterminateevent "Symfony\Component\Console\Event\ConsoleTerminateEvent") $event) After a command has been executed, it disables the output. | | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | | | | [write](#method_write)(array $record) {@inheritdoc} | | | | [getDefaultFormatter](#method_getDefaultFormatter)() {@inheritdoc} | | Details ------- ### \_\_construct([OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") $output = null, bool $bubble = true, array $verbosityLevelMap = array()) #### Parameters | | | | | --- | --- | --- | | [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") | $output | The console output to use (the handler remains disabled when passing null until the output is set, e.g. by using console events) | | bool | $bubble | Whether the messages that are handled can bubble up the stack | | array | $verbosityLevelMap | Array that maps the OutputInterface verbosity to a minimum logging level (leave empty to use the default mapping) | ### isHandling(array $record) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | array | $record | | ### handle(array $record) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | array | $record | | ### setOutput([OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") $output) Sets the console output to use for printing logs. #### Parameters | | | | | --- | --- | --- | | [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") | $output | | ### close() Disables the output. ### onCommand([ConsoleCommandEvent](../../../component/console/event/consolecommandevent "Symfony\Component\Console\Event\ConsoleCommandEvent") $event) Before a command is executed, the handler gets activated and the console output is set in order to know where to write the logs. #### Parameters | | | | | --- | --- | --- | | [ConsoleCommandEvent](../../../component/console/event/consolecommandevent "Symfony\Component\Console\Event\ConsoleCommandEvent") | $event | | ### onTerminate([ConsoleTerminateEvent](../../../component/console/event/consoleterminateevent "Symfony\Component\Console\Event\ConsoleTerminateEvent") $event) After a command has been executed, it disables the output. #### Parameters | | | | | --- | --- | --- | | [ConsoleTerminateEvent](../../../component/console/event/consoleterminateevent "Symfony\Component\Console\Event\ConsoleTerminateEvent") | $event | | ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to | ### protected write(array $record) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | array | $record | | ### protected getDefaultFormatter() {@inheritdoc} symfony SwiftMailerHandler SwiftMailerHandler =================== class **SwiftMailerHandler** extends SwiftMailerHandler Extended SwiftMailerHandler that flushes mail queue if necessary. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $transport | | | | protected | $instantFlush | | | Methods ------- | | | | | --- | --- | --- | | | [setTransport](#method_setTransport)(Swift\_Transport $transport) | | | | [onKernelTerminate](#method_onKernelTerminate)([PostResponseEvent](../../../component/httpkernel/event/postresponseevent "Symfony\Component\HttpKernel\Event\PostResponseEvent") $event) After the kernel has been terminated we will always flush messages. | | | | [onCliTerminate](#method_onCliTerminate)([ConsoleTerminateEvent](../../../component/console/event/consoleterminateevent "Symfony\Component\Console\Event\ConsoleTerminateEvent") $event) After the CLI application has been terminated we will always flush messages. | | | | [send](#method_send)($content, array $records) {@inheritdoc} | | Details ------- ### setTransport(Swift\_Transport $transport) #### Parameters | | | | | --- | --- | --- | | Swift\_Transport | $transport | | ### onKernelTerminate([PostResponseEvent](../../../component/httpkernel/event/postresponseevent "Symfony\Component\HttpKernel\Event\PostResponseEvent") $event) After the kernel has been terminated we will always flush messages. #### Parameters | | | | | --- | --- | --- | | [PostResponseEvent](../../../component/httpkernel/event/postresponseevent "Symfony\Component\HttpKernel\Event\PostResponseEvent") | $event | | ### onCliTerminate([ConsoleTerminateEvent](../../../component/console/event/consoleterminateevent "Symfony\Component\Console\Event\ConsoleTerminateEvent") $event) After the CLI application has been terminated we will always flush messages. #### Parameters | | | | | --- | --- | --- | | [ConsoleTerminateEvent](../../../component/console/event/consoleterminateevent "Symfony\Component\Console\Event\ConsoleTerminateEvent") | $event | | ### protected send($content, array $records) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | | $content | | | array | $records | | symfony ChromePhpHandler ChromePhpHandler ================= class **ChromePhpHandler** extends ChromePHPHandler ChromePhpHandler. Methods ------- | | | | | --- | --- | --- | | | [onKernelResponse](#method_onKernelResponse)([FilterResponseEvent](../../../component/httpkernel/event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) Adds the headers to the response once it's created. | | | | [sendHeader](#method_sendHeader)($header, $content) {@inheritdoc} | | | | [headersAccepted](#method_headersAccepted)() Override default behavior since we check it in onKernelResponse. | | Details ------- ### onKernelResponse([FilterResponseEvent](../../../component/httpkernel/event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) Adds the headers to the response once it's created. #### Parameters | | | | | --- | --- | --- | | [FilterResponseEvent](../../../component/httpkernel/event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") | $event | | ### protected sendHeader($header, $content) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | | $header | | | | $content | | ### protected headersAccepted() Override default behavior since we check it in onKernelResponse. symfony HttpCodeActivationStrategy HttpCodeActivationStrategy =========================== class **HttpCodeActivationStrategy** extends ErrorLevelActivationStrategy Activation strategy that ignores certain HTTP codes. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([RequestStack](../../../../component/httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack, array $exclusions, $actionLevel) | | | | [isHandlerActivated](#method_isHandlerActivated)(array $record) | | Details ------- ### \_\_construct([RequestStack](../../../../component/httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack, array $exclusions, $actionLevel) #### Parameters | | | | | --- | --- | --- | | [RequestStack](../../../../component/httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") | $requestStack | | | array | $exclusions | | | | $actionLevel | | ### isHandlerActivated(array $record) #### Parameters | | | | | --- | --- | --- | | array | $record | | symfony NotFoundActivationStrategy NotFoundActivationStrategy =========================== class **NotFoundActivationStrategy** extends ErrorLevelActivationStrategy Activation strategy that ignores 404s for certain URLs. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([RequestStack](../../../../component/httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack, array $excludedUrls, $actionLevel) | | | | [isHandlerActivated](#method_isHandlerActivated)(array $record) | | Details ------- ### \_\_construct([RequestStack](../../../../component/httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack, array $excludedUrls, $actionLevel) #### Parameters | | | | | --- | --- | --- | | [RequestStack](../../../../component/httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") | $requestStack | | | array | $excludedUrls | | | | $actionLevel | | ### isHandlerActivated(array $record) #### Parameters | | | | | --- | --- | --- | | array | $record | | symfony TokenProcessor TokenProcessor =============== class **TokenProcessor** Adds the current security token to the log entry. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([TokenStorageInterface](../../../component/security/core/authentication/token/storage/tokenstorageinterface "Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface") $tokenStorage) | | | | [\_\_invoke](#method___invoke)(array $records) | | Details ------- ### \_\_construct([TokenStorageInterface](../../../component/security/core/authentication/token/storage/tokenstorageinterface "Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface") $tokenStorage) #### Parameters | | | | | --- | --- | --- | | [TokenStorageInterface](../../../component/security/core/authentication/token/storage/tokenstorageinterface "Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface") | $tokenStorage | | ### \_\_invoke(array $records) #### Parameters | | | | | --- | --- | --- | | array | $records | | symfony WebProcessor WebProcessor ============= class **WebProcessor** extends WebProcessor implements [EventSubscriberInterface](../../../component/eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") WebProcessor override to read from the HttpFoundation's Request. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(array $extraFields = null) | | | | [onKernelRequest](#method_onKernelRequest)([GetResponseEvent](../../../component/httpkernel/event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) | | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | | Details ------- ### \_\_construct(array $extraFields = null) #### Parameters | | | | | --- | --- | --- | | array | $extraFields | | ### onKernelRequest([GetResponseEvent](../../../component/httpkernel/event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) #### Parameters | | | | | --- | --- | --- | | [GetResponseEvent](../../../component/httpkernel/event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") | $event | | ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to | symfony DebugProcessor DebugProcessor =============== class **DebugProcessor** implements [DebugLoggerInterface](../../../component/httpkernel/log/debugloggerinterface "Symfony\Component\HttpKernel\Log\DebugLoggerInterface") Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([RequestStack](../../../component/httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack = null) | | | | [\_\_invoke](#method___invoke)(array $record) | | | array | [getLogs](#method_getLogs)() Returns an array of logs. | | | int | [countErrors](#method_countErrors)() Returns the number of errors. | | | | [clear](#method_clear)() Removes all log records. | | Details ------- ### \_\_construct([RequestStack](../../../component/httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack = null) #### Parameters | | | | | --- | --- | --- | | [RequestStack](../../../component/httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") | $requestStack | | ### \_\_invoke(array $record) #### Parameters | | | | | --- | --- | --- | | array | $record | | ### array getLogs() Returns an array of logs. A log is an array with the following mandatory keys: timestamp, message, priority, and priorityName. It can also have an optional context key containing an array. #### Return Value | | | | --- | --- | | array | An array of logs | ### int countErrors() Returns the number of errors. #### Return Value | | | | --- | --- | | int | The number of errors | ### clear() Removes all log records. symfony ConsoleFormatter ConsoleFormatter ================= class **ConsoleFormatter** implements FormatterInterface Formats incoming records for console output by coloring them depending on log level. Constants --------- | | | | --- | --- | | SIMPLE\_FORMAT | | | SIMPLE\_DATE | | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(array $options = array()) Available options: \* format: The format of the outputted log string. The following placeholders are supported: %datetime%, %start\_tag%, %level\_name%, %end\_tag%, %channel%, %message%, %context%, %extra%; \* date\_format: The format of the outputted date string; \* colors: If true, the log string contains ANSI code to add color; \* multiline: If false, "context" and "extra" are dumped on one line. | | | | [formatBatch](#method_formatBatch)(array $records) {@inheritdoc} | | | | [format](#method_format)(array $record) {@inheritdoc} | | | | [echoLine](#method_echoLine)($line, $depth, $indentPad) | | | | [castObject](#method_castObject)($v, array $a, [Stub](../../../component/vardumper/cloner/stub "Symfony\Component\VarDumper\Cloner\Stub") $s, $isNested) | | Details ------- ### \_\_construct(array $options = array()) Available options: \* format: The format of the outputted log string. The following placeholders are supported: %datetime%, %start\_tag%, %level\_name%, %end\_tag%, %channel%, %message%, %context%, %extra%; \* date\_format: The format of the outputted date string; \* colors: If true, the log string contains ANSI code to add color; \* multiline: If false, "context" and "extra" are dumped on one line. #### Parameters | | | | | --- | --- | --- | | array | $options | | ### formatBatch(array $records) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | array | $records | | ### format(array $record) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | array | $record | | ### echoLine($line, $depth, $indentPad) #### Parameters | | | | | --- | --- | --- | | | $line | | | | $depth | | | | $indentPad | | ### castObject($v, array $a, [Stub](../../../component/vardumper/cloner/stub "Symfony\Component\VarDumper\Cloner\Stub") $s, $isNested) #### Parameters | | | | | --- | --- | --- | | | $v | | | array | $a | | | [Stub](../../../component/vardumper/cloner/stub "Symfony\Component\VarDumper\Cloner\Stub") | $s | | | | $isNested | | symfony VarDumperFormatter VarDumperFormatter =================== class **VarDumperFormatter** implements FormatterInterface Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([VarCloner](../../../component/vardumper/cloner/varcloner "Symfony\Component\VarDumper\Cloner\VarCloner") $cloner = null) | | | | [format](#method_format)(array $record) | | | | [formatBatch](#method_formatBatch)(array $records) | | Details ------- ### \_\_construct([VarCloner](../../../component/vardumper/cloner/varcloner "Symfony\Component\VarDumper\Cloner\VarCloner") $cloner = null) #### Parameters | | | | | --- | --- | --- | | [VarCloner](../../../component/vardumper/cloner/varcloner "Symfony\Component\VarDumper\Cloner\VarCloner") | $cloner | | ### format(array $record) #### Parameters | | | | | --- | --- | --- | | array | $record | | ### formatBatch(array $records) #### Parameters | | | | | --- | --- | --- | | array | $records | |
programming_docs
symfony Symfony\Bridge\Twig\Extension Symfony\Bridge\Twig\Extension ============================= Classes ------- | | | | --- | --- | | [AssetExtension](extension/assetextension "Symfony\Bridge\Twig\Extension\AssetExtension") | Twig extension for the Symfony Asset component. | | [CodeExtension](extension/codeextension "Symfony\Bridge\Twig\Extension\CodeExtension") | Twig extension relate to PHP code and used by the profiler and the default exception templates. | | [CsrfExtension](extension/csrfextension "Symfony\Bridge\Twig\Extension\CsrfExtension") | | | [CsrfRuntime](extension/csrfruntime "Symfony\Bridge\Twig\Extension\CsrfRuntime") | | | [DumpExtension](extension/dumpextension "Symfony\Bridge\Twig\Extension\DumpExtension") | Provides integration of the dump() function with Twig. | | [ExpressionExtension](extension/expressionextension "Symfony\Bridge\Twig\Extension\ExpressionExtension") | ExpressionExtension gives a way to create Expressions from a template. | | [FormExtension](extension/formextension "Symfony\Bridge\Twig\Extension\FormExtension") | FormExtension extends Twig with form capabilities. | | [HttpFoundationExtension](extension/httpfoundationextension "Symfony\Bridge\Twig\Extension\HttpFoundationExtension") | Twig extension for the Symfony HttpFoundation component. | | [HttpKernelExtension](extension/httpkernelextension "Symfony\Bridge\Twig\Extension\HttpKernelExtension") | Provides integration with the HttpKernel component. | | [HttpKernelRuntime](extension/httpkernelruntime "Symfony\Bridge\Twig\Extension\HttpKernelRuntime") | Provides integration with the HttpKernel component. | | [LogoutUrlExtension](extension/logouturlextension "Symfony\Bridge\Twig\Extension\LogoutUrlExtension") | LogoutUrlHelper provides generator functions for the logout URL to Twig. | | [ProfilerExtension](extension/profilerextension "Symfony\Bridge\Twig\Extension\ProfilerExtension") | | | [RoutingExtension](extension/routingextension "Symfony\Bridge\Twig\Extension\RoutingExtension") | Provides integration of the Routing component with Twig. | | [SecurityExtension](extension/securityextension "Symfony\Bridge\Twig\Extension\SecurityExtension") | SecurityExtension exposes security context features. | | [StopwatchExtension](extension/stopwatchextension "Symfony\Bridge\Twig\Extension\StopwatchExtension") | Twig extension for the stopwatch helper. | | [TranslationExtension](extension/translationextension "Symfony\Bridge\Twig\Extension\TranslationExtension") | Provides integration of the Translation component with Twig. | | [WebLinkExtension](extension/weblinkextension "Symfony\Bridge\Twig\Extension\WebLinkExtension") | Twig extension for the Symfony WebLink component. | | [WorkflowExtension](extension/workflowextension "Symfony\Bridge\Twig\Extension\WorkflowExtension") | WorkflowExtension. | | [YamlExtension](extension/yamlextension "Symfony\Bridge\Twig\Extension\YamlExtension") | Provides integration of the Yaml component with Twig. | symfony Symfony\Bridge\Twig\Node Symfony\Bridge\Twig\Node ======================== Classes ------- | | | | --- | --- | | [DumpNode](node/dumpnode "Symfony\Bridge\Twig\Node\DumpNode") | | | [FormThemeNode](node/formthemenode "Symfony\Bridge\Twig\Node\FormThemeNode") | | | [RenderBlockNode](node/renderblocknode "Symfony\Bridge\Twig\Node\RenderBlockNode") | Compiles a call to {@link \Symfony\Component\Form\FormRendererInterface::renderBlock()}. | | [SearchAndRenderBlockNode](node/searchandrenderblocknode "Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode") | | | [StopwatchNode](node/stopwatchnode "Symfony\Bridge\Twig\Node\StopwatchNode") | Represents a stopwatch node. | | [TransDefaultDomainNode](node/transdefaultdomainnode "Symfony\Bridge\Twig\Node\TransDefaultDomainNode") | | | [TransNode](node/transnode "Symfony\Bridge\Twig\Node\TransNode") | | symfony Symfony\Bridge\Twig\Form Symfony\Bridge\Twig\Form ======================== Classes ------- | | | | --- | --- | | [TwigRendererEngine](form/twigrendererengine "Symfony\Bridge\Twig\Form\TwigRendererEngine") | | symfony UndefinedCallableHandler UndefinedCallableHandler ========================= class **UndefinedCallableHandler** Methods ------- | | | | | --- | --- | --- | | static | [onUndefinedFilter](#method_onUndefinedFilter)($name) | | | static | [onUndefinedFunction](#method_onUndefinedFunction)($name) | | Details ------- ### static onUndefinedFilter($name) #### Parameters | | | | | --- | --- | --- | | | $name | | ### static onUndefinedFunction($name) #### Parameters | | | | | --- | --- | --- | | | $name | | symfony Symfony\Bridge\Twig\DataCollector Symfony\Bridge\Twig\DataCollector ================================= Classes ------- | | | | --- | --- | | [TwigDataCollector](datacollector/twigdatacollector "Symfony\Bridge\Twig\DataCollector\TwigDataCollector") | TwigDataCollector. | symfony Symfony\Bridge\Twig\Translation Symfony\Bridge\Twig\Translation =============================== Classes ------- | | | | --- | --- | | [TwigExtractor](translation/twigextractor "Symfony\Bridge\Twig\Translation\TwigExtractor") | TwigExtractor extracts translation messages from a twig template. | symfony Symfony\Bridge\Twig\Command Symfony\Bridge\Twig\Command =========================== Classes ------- | | | | --- | --- | | [DebugCommand](command/debugcommand "Symfony\Bridge\Twig\Command\DebugCommand") | Lists twig functions, filters, globals and tests present in the current project. | | [LintCommand](command/lintcommand "Symfony\Bridge\Twig\Command\LintCommand") | Command that will validate your template syntax and output encountered errors. | symfony AppVariable AppVariable ============ class **AppVariable** Exposes some Symfony parameters and services as an "app" global variable. Methods ------- | | | | | --- | --- | --- | | | [setTokenStorage](#method_setTokenStorage)([TokenStorageInterface](../../component/security/core/authentication/token/storage/tokenstorageinterface "Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface") $tokenStorage) | | | | [setRequestStack](#method_setRequestStack)([RequestStack](../../component/httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack) | | | | [setEnvironment](#method_setEnvironment)($environment) | | | | [setDebug](#method_setDebug)($debug) | | | [TokenInterface](../../component/security/core/authentication/token/tokeninterface "Symfony\Component\Security\Core\Authentication\Token\TokenInterface")|null | [getToken](#method_getToken)() Returns the current token. | | | mixed | [getUser](#method_getUser)() Returns the current user. | | | [Request](../../component/httpfoundation/request "Symfony\Component\HttpFoundation\Request")|null | [getRequest](#method_getRequest)() Returns the current request. | | | [Session](../../component/httpfoundation/session/session "Symfony\Component\HttpFoundation\Session\Session")|null | [getSession](#method_getSession)() Returns the current session. | | | string | [getEnvironment](#method_getEnvironment)() Returns the current app environment. | | | bool | [getDebug](#method_getDebug)() Returns the current app debug mode. | | | array | [getFlashes](#method_getFlashes)($types = null) Returns some or all the existing flash messages: \* getFlashes() returns all the flash messages \* getFlashes('notice') returns a simple array with flash messages of that type \* getFlashes(array('notice', 'error')) returns a nested array of type => messages. | | Details ------- ### setTokenStorage([TokenStorageInterface](../../component/security/core/authentication/token/storage/tokenstorageinterface "Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface") $tokenStorage) #### Parameters | | | | | --- | --- | --- | | [TokenStorageInterface](../../component/security/core/authentication/token/storage/tokenstorageinterface "Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface") | $tokenStorage | | ### setRequestStack([RequestStack](../../component/httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack) #### Parameters | | | | | --- | --- | --- | | [RequestStack](../../component/httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") | $requestStack | | ### setEnvironment($environment) #### Parameters | | | | | --- | --- | --- | | | $environment | | ### setDebug($debug) #### Parameters | | | | | --- | --- | --- | | | $debug | | ### [TokenInterface](../../component/security/core/authentication/token/tokeninterface "Symfony\Component\Security\Core\Authentication\Token\TokenInterface")|null getToken() Returns the current token. #### Return Value | | | | --- | --- | | [TokenInterface](../../component/security/core/authentication/token/tokeninterface "Symfony\Component\Security\Core\Authentication\Token\TokenInterface")|null | | #### Exceptions | | | | --- | --- | | [RuntimeException](http://php.net/RuntimeException) | When the TokenStorage is not available | ### mixed getUser() Returns the current user. #### Return Value | | | | --- | --- | | mixed | | #### See also | | | | --- | --- | | [TokenInterface::getUser](../../component/security/core/authentication/token/tokeninterface#method_getUser "Symfony\Component\Security\Core\Authentication\Token\TokenInterface") | | ### [Request](../../component/httpfoundation/request "Symfony\Component\HttpFoundation\Request")|null getRequest() Returns the current request. #### Return Value | | | | --- | --- | | [Request](../../component/httpfoundation/request "Symfony\Component\HttpFoundation\Request")|null | The HTTP request object | ### [Session](../../component/httpfoundation/session/session "Symfony\Component\HttpFoundation\Session\Session")|null getSession() Returns the current session. #### Return Value | | | | --- | --- | | [Session](../../component/httpfoundation/session/session "Symfony\Component\HttpFoundation\Session\Session")|null | The session | ### string getEnvironment() Returns the current app environment. #### Return Value | | | | --- | --- | | string | The current environment string (e.g 'dev') | ### bool getDebug() Returns the current app debug mode. #### Return Value | | | | --- | --- | | bool | The current debug mode | ### array getFlashes($types = null) Returns some or all the existing flash messages: \* getFlashes() returns all the flash messages \* getFlashes('notice') returns a simple array with flash messages of that type \* getFlashes(array('notice', 'error')) returns a nested array of type => messages. #### Parameters | | | | | --- | --- | --- | | | $types | | #### Return Value | | | | --- | --- | | array | | symfony Symfony\Bridge\Twig\TokenParser Symfony\Bridge\Twig\TokenParser =============================== Classes ------- | | | | --- | --- | | [DumpTokenParser](tokenparser/dumptokenparser "Symfony\Bridge\Twig\TokenParser\DumpTokenParser") | Token Parser for the 'dump' tag. | | [FormThemeTokenParser](tokenparser/formthemetokenparser "Symfony\Bridge\Twig\TokenParser\FormThemeTokenParser") | Token Parser for the 'form\_theme' tag. | | [StopwatchTokenParser](tokenparser/stopwatchtokenparser "Symfony\Bridge\Twig\TokenParser\StopwatchTokenParser") | Token Parser for the stopwatch tag. | | [TransChoiceTokenParser](tokenparser/transchoicetokenparser "Symfony\Bridge\Twig\TokenParser\TransChoiceTokenParser") | Token Parser for the 'transchoice' tag. | | [TransDefaultDomainTokenParser](tokenparser/transdefaultdomaintokenparser "Symfony\Bridge\Twig\TokenParser\TransDefaultDomainTokenParser") | Token Parser for the 'trans\_default\_domain' tag. | | [TransTokenParser](tokenparser/transtokenparser "Symfony\Bridge\Twig\TokenParser\TransTokenParser") | Token Parser for the 'trans' tag. | symfony TwigEngine TwigEngine =========== class **TwigEngine** implements [EngineInterface](../../component/templating/engineinterface "Symfony\Component\Templating\EngineInterface"), [StreamingEngineInterface](../../component/templating/streamingengineinterface "Symfony\Component\Templating\StreamingEngineInterface") This engine knows how to render Twig templates. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $environment | | | | protected | $parser | | | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(Environment $environment, [TemplateNameParserInterface](../../component/templating/templatenameparserinterface "Symfony\Component\Templating\TemplateNameParserInterface") $parser) | | | string | [render](#method_render)(string|[TemplateReferenceInterface](../../component/templating/templatereferenceinterface "Symfony\Component\Templating\TemplateReferenceInterface") $name, array $parameters = array()) Renders a template. | | | | [stream](#method_stream)(string|[TemplateReferenceInterface](../../component/templating/templatereferenceinterface "Symfony\Component\Templating\TemplateReferenceInterface") $name, array $parameters = array()) Streams a template. | | | bool | [exists](#method_exists)(string|[TemplateReferenceInterface](../../component/templating/templatereferenceinterface "Symfony\Component\Templating\TemplateReferenceInterface") $name) Returns true if the template exists. | | | bool | [supports](#method_supports)(string|[TemplateReferenceInterface](../../component/templating/templatereferenceinterface "Symfony\Component\Templating\TemplateReferenceInterface") $name) Returns true if this class is able to render the given template. | | | Template | [load](#method_load)(string|[TemplateReferenceInterface](../../component/templating/templatereferenceinterface "Symfony\Component\Templating\TemplateReferenceInterface")|Template $name) Loads the given template. | | Details ------- ### \_\_construct(Environment $environment, [TemplateNameParserInterface](../../component/templating/templatenameparserinterface "Symfony\Component\Templating\TemplateNameParserInterface") $parser) #### Parameters | | | | | --- | --- | --- | | Environment | $environment | | | [TemplateNameParserInterface](../../component/templating/templatenameparserinterface "Symfony\Component\Templating\TemplateNameParserInterface") | $parser | | ### string render(string|[TemplateReferenceInterface](../../component/templating/templatereferenceinterface "Symfony\Component\Templating\TemplateReferenceInterface") $name, array $parameters = array()) Renders a template. #### Parameters | | | | | --- | --- | --- | | string|[TemplateReferenceInterface](../../component/templating/templatereferenceinterface "Symfony\Component\Templating\TemplateReferenceInterface") | $name | A template name or a TemplateReferenceInterface instance | | array | $parameters | An array of parameters to pass to the template | #### Return Value | | | | --- | --- | | string | The evaluated template as a string | #### Exceptions | | | | --- | --- | | [RuntimeException](http://php.net/RuntimeException) | if the template cannot be rendered | ### stream(string|[TemplateReferenceInterface](../../component/templating/templatereferenceinterface "Symfony\Component\Templating\TemplateReferenceInterface") $name, array $parameters = array()) Streams a template. The implementation should output the content directly to the client. #### Parameters | | | | | --- | --- | --- | | string|[TemplateReferenceInterface](../../component/templating/templatereferenceinterface "Symfony\Component\Templating\TemplateReferenceInterface") | $name | A template name or a TemplateReferenceInterface instance | | array | $parameters | An array of parameters to pass to the template | #### Exceptions | | | | --- | --- | | [RuntimeException](http://php.net/RuntimeException) | if the template cannot be rendered | | [LogicException](http://php.net/LogicException) | if the template cannot be streamed | ### bool exists(string|[TemplateReferenceInterface](../../component/templating/templatereferenceinterface "Symfony\Component\Templating\TemplateReferenceInterface") $name) Returns true if the template exists. #### Parameters | | | | | --- | --- | --- | | string|[TemplateReferenceInterface](../../component/templating/templatereferenceinterface "Symfony\Component\Templating\TemplateReferenceInterface") | $name | A template name or a TemplateReferenceInterface instance | #### Return Value | | | | --- | --- | | bool | true if the template exists, false otherwise | #### Exceptions | | | | --- | --- | | [RuntimeException](http://php.net/RuntimeException) | if the engine cannot handle the template name | ### bool supports(string|[TemplateReferenceInterface](../../component/templating/templatereferenceinterface "Symfony\Component\Templating\TemplateReferenceInterface") $name) Returns true if this class is able to render the given template. #### Parameters | | | | | --- | --- | --- | | string|[TemplateReferenceInterface](../../component/templating/templatereferenceinterface "Symfony\Component\Templating\TemplateReferenceInterface") | $name | A template name or a TemplateReferenceInterface instance | #### Return Value | | | | --- | --- | | bool | true if this class supports the given template, false otherwise | ### protected Template load(string|[TemplateReferenceInterface](../../component/templating/templatereferenceinterface "Symfony\Component\Templating\TemplateReferenceInterface")|Template $name) Loads the given template. #### Parameters | | | | | --- | --- | --- | | string|[TemplateReferenceInterface](../../component/templating/templatereferenceinterface "Symfony\Component\Templating\TemplateReferenceInterface")|Template | $name | A template name or an instance of TemplateReferenceInterface or Template | #### Return Value | | | | --- | --- | | Template | | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](http://php.net/InvalidArgumentException) | if the template does not exist | symfony Symfony\Bridge\Twig\NodeVisitor Symfony\Bridge\Twig\NodeVisitor =============================== Classes ------- | | | | --- | --- | | [Scope](nodevisitor/scope "Symfony\Bridge\Twig\NodeVisitor\Scope") | | | [TranslationDefaultDomainNodeVisitor](nodevisitor/translationdefaultdomainnodevisitor "Symfony\Bridge\Twig\NodeVisitor\TranslationDefaultDomainNodeVisitor") | | | [TranslationNodeVisitor](nodevisitor/translationnodevisitor "Symfony\Bridge\Twig\NodeVisitor\TranslationNodeVisitor") | TranslationNodeVisitor extracts translation messages. | symfony TwigDataCollector TwigDataCollector ================== class **TwigDataCollector** extends [DataCollector](../../../component/httpkernel/datacollector/datacollector "Symfony\Component\HttpKernel\DataCollector\DataCollector") implements [LateDataCollectorInterface](../../../component/httpkernel/datacollector/latedatacollectorinterface "Symfony\Component\HttpKernel\DataCollector\LateDataCollectorInterface") TwigDataCollector. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $data | | from [DataCollector](../../../component/httpkernel/datacollector/datacollector#property_data "Symfony\Component\HttpKernel\DataCollector\DataCollector") | Methods ------- | | | | | --- | --- | --- | | | [serialize](#method_serialize)() | from [DataCollector](../../../component/httpkernel/datacollector/datacollector#method_serialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [unserialize](#method_unserialize)($data) | from [DataCollector](../../../component/httpkernel/datacollector/datacollector#method_unserialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | [Data](../../../component/vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | [cloneVar](#method_cloneVar)(mixed $var) Converts the variable into a serializable Data instance. | from [DataCollector](../../../component/httpkernel/datacollector/datacollector#method_cloneVar "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | callable[] | [getCasters](#method_getCasters)() | from [DataCollector](../../../component/httpkernel/datacollector/datacollector#method_getCasters "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [\_\_construct](#method___construct)(Profile $profile, Environment $twig = null) | | | | [collect](#method_collect)([Request](../../../component/httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../../component/httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. | | | | [reset](#method_reset)() Resets this data collector to its initial state. | | | | [lateCollect](#method_lateCollect)() Collects data as late as possible. | | | | [getTime](#method_getTime)() | | | | [getTemplateCount](#method_getTemplateCount)() | | | | [getTemplatePaths](#method_getTemplatePaths)() | | | | [getTemplates](#method_getTemplates)() | | | | [getBlockCount](#method_getBlockCount)() | | | | [getMacroCount](#method_getMacroCount)() | | | | [getHtmlCallGraph](#method_getHtmlCallGraph)() | | | | [getProfile](#method_getProfile)() | | | string | [getName](#method_getName)() Returns the name of the collector. | | Details ------- ### serialize() ### unserialize($data) #### Parameters | | | | | --- | --- | --- | | | $data | | ### protected [Data](../../../component/vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") cloneVar(mixed $var) Converts the variable into a serializable Data instance. This array can be displayed in the template using the VarDumper component. #### Parameters | | | | | --- | --- | --- | | mixed | $var | | #### Return Value | | | | --- | --- | | [Data](../../../component/vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | | ### protected callable[] getCasters() #### Return Value | | | | --- | --- | | callable[] | The casters to add to the cloner | ### \_\_construct(Profile $profile, Environment $twig = null) #### Parameters | | | | | --- | --- | --- | | Profile | $profile | | | Environment | $twig | | ### collect([Request](../../../component/httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../../component/httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. #### Parameters | | | | | --- | --- | --- | | [Request](../../../component/httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../../component/httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | | [Exception](http://php.net/Exception) | $exception | | ### reset() Resets this data collector to its initial state. ### lateCollect() Collects data as late as possible. ### getTime() ### getTemplateCount() ### getTemplatePaths() ### getTemplates() ### getBlockCount() ### getMacroCount() ### getHtmlCallGraph() ### getProfile() ### string getName() Returns the name of the collector. #### Return Value | | | | --- | --- | | string | The collector name |
programming_docs
symfony TwigRendererEngine TwigRendererEngine =================== class **TwigRendererEngine** extends [AbstractRendererEngine](../../../component/form/abstractrendererengine "Symfony\Component\Form\AbstractRendererEngine") Constants --------- | | | | --- | --- | | CACHE\_KEY\_VAR | *The variable in {@link FormView} used as cache key.* | Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $defaultThemes | | from [AbstractRendererEngine](../../../component/form/abstractrendererengine#property_defaultThemes "Symfony\Component\Form\AbstractRendererEngine") | | protected | $themes | | from [AbstractRendererEngine](../../../component/form/abstractrendererengine#property_themes "Symfony\Component\Form\AbstractRendererEngine") | | protected | $useDefaultThemes | | from [AbstractRendererEngine](../../../component/form/abstractrendererengine#property_useDefaultThemes "Symfony\Component\Form\AbstractRendererEngine") | | protected | $resources | | from [AbstractRendererEngine](../../../component/form/abstractrendererengine#property_resources "Symfony\Component\Form\AbstractRendererEngine") | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(array $defaultThemes, Environment $environment) Creates a new renderer engine. | | | | [setTheme](#method_setTheme)([FormView](../../../component/form/formview "Symfony\Component\Form\FormView") $view, mixed $themes, bool $useDefaultThemes = true) Sets the theme(s) to be used for rendering a view and its children. | from [AbstractRendererEngine](../../../component/form/abstractrendererengine#method_setTheme "Symfony\Component\Form\AbstractRendererEngine") | | mixed | [getResourceForBlockName](#method_getResourceForBlockName)([FormView](../../../component/form/formview "Symfony\Component\Form\FormView") $view, string $blockName) Returns the resource for a block name. | from [AbstractRendererEngine](../../../component/form/abstractrendererengine#method_getResourceForBlockName "Symfony\Component\Form\AbstractRendererEngine") | | mixed | [getResourceForBlockNameHierarchy](#method_getResourceForBlockNameHierarchy)([FormView](../../../component/form/formview "Symfony\Component\Form\FormView") $view, array $blockNameHierarchy, int $hierarchyLevel) Returns the resource for a block hierarchy. | from [AbstractRendererEngine](../../../component/form/abstractrendererengine#method_getResourceForBlockNameHierarchy "Symfony\Component\Form\AbstractRendererEngine") | | int|bool | [getResourceHierarchyLevel](#method_getResourceHierarchyLevel)([FormView](../../../component/form/formview "Symfony\Component\Form\FormView") $view, array $blockNameHierarchy, int $hierarchyLevel) Returns the hierarchy level at which a resource can be found. | from [AbstractRendererEngine](../../../component/form/abstractrendererengine#method_getResourceHierarchyLevel "Symfony\Component\Form\AbstractRendererEngine") | | bool | [loadResourceForBlockName](#method_loadResourceForBlockName)(string $cacheKey, [FormView](../../../component/form/formview "Symfony\Component\Form\FormView") $view, string $blockName) Loads the cache with the resource for a given block name. | | | string | [renderBlock](#method_renderBlock)([FormView](../../../component/form/formview "Symfony\Component\Form\FormView") $view, mixed $resource, string $blockName, array $variables = array()) Renders a block in the given renderer resource. | | | | [loadResourcesFromTheme](#method_loadResourcesFromTheme)(string $cacheKey, mixed $theme) Loads the resources for all blocks in a theme. | | Details ------- ### \_\_construct(array $defaultThemes, Environment $environment) Creates a new renderer engine. #### Parameters | | | | | --- | --- | --- | | array | $defaultThemes | The default themes. The type of these themes is open to the implementation. | | Environment | $environment | | ### setTheme([FormView](../../../component/form/formview "Symfony\Component\Form\FormView") $view, mixed $themes, bool $useDefaultThemes = true) Sets the theme(s) to be used for rendering a view and its children. #### Parameters | | | | | --- | --- | --- | | [FormView](../../../component/form/formview "Symfony\Component\Form\FormView") | $view | The view to assign the theme(s) to | | mixed | $themes | The theme(s). The type of these themes is open to the implementation. | | bool | $useDefaultThemes | If true, will use default themes specified in the engine | ### mixed getResourceForBlockName([FormView](../../../component/form/formview "Symfony\Component\Form\FormView") $view, string $blockName) Returns the resource for a block name. The resource is first searched in the themes attached to $view, then in the themes of its parent view and so on, until a resource was found. The type of the resource is decided by the implementation. The resource is later passed to {@link renderBlock()} by the rendering algorithm. #### Parameters | | | | | --- | --- | --- | | [FormView](../../../component/form/formview "Symfony\Component\Form\FormView") | $view | the view for determining the used themes. First the themes attached directly to the view with {@link setTheme()} are considered, then the ones of its parent etc | | string | $blockName | The name of the block to render | #### Return Value | | | | --- | --- | | mixed | the renderer resource or false, if none was found | ### mixed getResourceForBlockNameHierarchy([FormView](../../../component/form/formview "Symfony\Component\Form\FormView") $view, array $blockNameHierarchy, int $hierarchyLevel) Returns the resource for a block hierarchy. A block hierarchy is an array which starts with the root of the hierarchy and continues with the child of that root, the child of that child etc. The following is an example for a block hierarchy: ``` form_widget text_widget url_widget ``` In this example, "url\_widget" is the most specific block, while the other blocks are its ancestors in the hierarchy. The second parameter $hierarchyLevel determines the level of the hierarchy that should be rendered. For example, if $hierarchyLevel is 2 for the above hierarchy, the engine will first look for the block "url\_widget", then, if that does not exist, for the block "text\_widget" etc. The type of the resource is decided by the implementation. The resource is later passed to {@link renderBlock()} by the rendering algorithm. #### Parameters | | | | | --- | --- | --- | | [FormView](../../../component/form/formview "Symfony\Component\Form\FormView") | $view | the view for determining the used themes. First the themes attached directly to the view with {@link setTheme()} are considered, then the ones of its parent etc | | array | $blockNameHierarchy | The block name hierarchy, with the root block at the beginning | | int | $hierarchyLevel | The level in the hierarchy at which to start looking. Level 0 indicates the root block, i.e. the first element of $blockNameHierarchy. | #### Return Value | | | | --- | --- | | mixed | The renderer resource or false, if none was found | ### int|bool getResourceHierarchyLevel([FormView](../../../component/form/formview "Symfony\Component\Form\FormView") $view, array $blockNameHierarchy, int $hierarchyLevel) Returns the hierarchy level at which a resource can be found. A block hierarchy is an array which starts with the root of the hierarchy and continues with the child of that root, the child of that child etc. The following is an example for a block hierarchy: ``` form_widget text_widget url_widget ``` The second parameter $hierarchyLevel determines the level of the hierarchy that should be rendered. If we call this method with the hierarchy level 2, the engine will first look for a resource for block "url\_widget". If such a resource exists, the method returns 2. Otherwise it tries to find a resource for block "text\_widget" (at level 1) and, again, returns 1 if a resource was found. The method continues to look for resources until the root level was reached and nothing was found. In this case false is returned. The type of the resource is decided by the implementation. The resource is later passed to {@link renderBlock()} by the rendering algorithm. #### Parameters | | | | | --- | --- | --- | | [FormView](../../../component/form/formview "Symfony\Component\Form\FormView") | $view | the view for determining the used themes. First the themes attached directly to the view with {@link setTheme()} are considered, then the ones of its parent etc | | array | $blockNameHierarchy | The block name hierarchy, with the root block at the beginning | | int | $hierarchyLevel | The level in the hierarchy at which to start looking. Level 0 indicates the root block, i.e. the first element of $blockNameHierarchy. | #### Return Value | | | | --- | --- | | int|bool | The hierarchy level or false, if no resource was found | ### protected bool loadResourceForBlockName(string $cacheKey, [FormView](../../../component/form/formview "Symfony\Component\Form\FormView") $view, string $blockName) Loads the cache with the resource for a given block name. This implementation eagerly loads all blocks of the themes assigned to the given view and all of its ancestors views. This is necessary, because Twig receives the list of blocks later. At that point, all blocks must already be loaded, for the case that the function "block()" is used in the Twig template. #### Parameters | | | | | --- | --- | --- | | string | $cacheKey | The cache key of the form view | | [FormView](../../../component/form/formview "Symfony\Component\Form\FormView") | $view | The form view for finding the applying themes | | string | $blockName | The name of the block to load | #### Return Value | | | | --- | --- | | bool | True if the resource could be loaded, false otherwise | #### See also | | | | --- | --- | | getResourceForBlock() | | ### string renderBlock([FormView](../../../component/form/formview "Symfony\Component\Form\FormView") $view, mixed $resource, string $blockName, array $variables = array()) Renders a block in the given renderer resource. The resource can be obtained by calling {@link getResourceForBlock()} or {@link getResourceForBlockHierarchy()}. The type of the resource is decided by the implementation. #### Parameters | | | | | --- | --- | --- | | [FormView](../../../component/form/formview "Symfony\Component\Form\FormView") | $view | The view to render | | mixed | $resource | The renderer resource | | string | $blockName | The name of the block to render | | array | $variables | The variables to pass to the template | #### Return Value | | | | --- | --- | | string | The HTML markup | ### protected loadResourcesFromTheme(string $cacheKey, mixed $theme) Loads the resources for all blocks in a theme. #### Parameters | | | | | --- | --- | --- | | string | $cacheKey | The cache key for storing the resource | | mixed | $theme | The theme to load the block from. This parameter is passed by reference, because it might be necessary to initialize the theme first. Any changes made to this variable will be kept and be available upon further calls to this method using the same theme. | symfony StopwatchExtension StopwatchExtension =================== class **StopwatchExtension** extends AbstractExtension Twig extension for the stopwatch helper. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([Stopwatch](../../../component/stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") $stopwatch = null, bool $enabled = true) | | | | [getStopwatch](#method_getStopwatch)() | | | | [getTokenParsers](#method_getTokenParsers)() | | | | [getName](#method_getName)() | | Details ------- ### \_\_construct([Stopwatch](../../../component/stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") $stopwatch = null, bool $enabled = true) #### Parameters | | | | | --- | --- | --- | | [Stopwatch](../../../component/stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") | $stopwatch | | | bool | $enabled | | ### getStopwatch() ### getTokenParsers() ### getName() symfony WorkflowExtension WorkflowExtension ================== class **WorkflowExtension** extends AbstractExtension WorkflowExtension. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([Registry](../../../component/workflow/registry "Symfony\Component\Workflow\Registry") $workflowRegistry) | | | | [getFunctions](#method_getFunctions)() | | | bool | [canTransition](#method_canTransition)(object $subject, string $transitionName, string $name = null) Returns true if the transition is enabled. | | | [Transition](../../../component/workflow/transition "Symfony\Component\Workflow\Transition")[] | [getEnabledTransitions](#method_getEnabledTransitions)(object $subject, string $name = null) Returns all enabled transitions. | | | bool | [hasMarkedPlace](#method_hasMarkedPlace)(object $subject, string $placeName, string $name = null) Returns true if the place is marked. | | | string[]|int[] | [getMarkedPlaces](#method_getMarkedPlaces)(object $subject, bool $placesNameOnly = true, string $name = null) Returns marked places. | | | string|null | [getMetadata](#method_getMetadata)($subject, string $key, $metadataSubject = null, string $name = null) Returns the metadata for a specific subject. | | | | [getName](#method_getName)() | | Details ------- ### \_\_construct([Registry](../../../component/workflow/registry "Symfony\Component\Workflow\Registry") $workflowRegistry) #### Parameters | | | | | --- | --- | --- | | [Registry](../../../component/workflow/registry "Symfony\Component\Workflow\Registry") | $workflowRegistry | | ### getFunctions() ### bool canTransition(object $subject, string $transitionName, string $name = null) Returns true if the transition is enabled. #### Parameters | | | | | --- | --- | --- | | object | $subject | A subject | | string | $transitionName | A transition | | string | $name | A workflow name | #### Return Value | | | | --- | --- | | bool | true if the transition is enabled | ### [Transition](../../../component/workflow/transition "Symfony\Component\Workflow\Transition")[] getEnabledTransitions(object $subject, string $name = null) Returns all enabled transitions. #### Parameters | | | | | --- | --- | --- | | object | $subject | A subject | | string | $name | A workflow name | #### Return Value | | | | --- | --- | | [Transition](../../../component/workflow/transition "Symfony\Component\Workflow\Transition")[] | All enabled transitions | ### bool hasMarkedPlace(object $subject, string $placeName, string $name = null) Returns true if the place is marked. #### Parameters | | | | | --- | --- | --- | | object | $subject | A subject | | string | $placeName | A place name | | string | $name | A workflow name | #### Return Value | | | | --- | --- | | bool | true if the transition is enabled | ### string[]|int[] getMarkedPlaces(object $subject, bool $placesNameOnly = true, string $name = null) Returns marked places. #### Parameters | | | | | --- | --- | --- | | object | $subject | A subject | | bool | $placesNameOnly | If true, returns only places name. If false returns the raw representation | | string | $name | A workflow name | #### Return Value | | | | --- | --- | | string[]|int[] | | ### string|null getMetadata($subject, string $key, $metadataSubject = null, string $name = null) Returns the metadata for a specific subject. #### Parameters | | | | | --- | --- | --- | | | $subject | | | string | $key | | | | $metadataSubject | | | string | $name | | #### Return Value | | | | --- | --- | | string|null | | ### getName() symfony SecurityExtension SecurityExtension ================== class **SecurityExtension** extends AbstractExtension SecurityExtension exposes security context features. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([AuthorizationCheckerInterface](../../../component/security/core/authorization/authorizationcheckerinterface "Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface") $securityChecker = null) | | | | [isGranted](#method_isGranted)($role, $object = null, $field = null) | | | | [getFunctions](#method_getFunctions)() {@inheritdoc} | | | | [getName](#method_getName)() {@inheritdoc} | | Details ------- ### \_\_construct([AuthorizationCheckerInterface](../../../component/security/core/authorization/authorizationcheckerinterface "Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface") $securityChecker = null) #### Parameters | | | | | --- | --- | --- | | [AuthorizationCheckerInterface](../../../component/security/core/authorization/authorizationcheckerinterface "Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface") | $securityChecker | | ### isGranted($role, $object = null, $field = null) #### Parameters | | | | | --- | --- | --- | | | $role | | | | $object | | | | $field | | ### getFunctions() {@inheritdoc} ### getName() {@inheritdoc} symfony ProfilerExtension ProfilerExtension ================== class **ProfilerExtension** extends ProfilerExtension Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(Profile $profile, [Stopwatch](../../../component/stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") $stopwatch = null) | | | | [enter](#method_enter)(Profile $profile) | | | | [leave](#method_leave)(Profile $profile) | | | | [getName](#method_getName)() {@inheritdoc} | | Details ------- ### \_\_construct(Profile $profile, [Stopwatch](../../../component/stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") $stopwatch = null) #### Parameters | | | | | --- | --- | --- | | Profile | $profile | | | [Stopwatch](../../../component/stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") | $stopwatch | | ### enter(Profile $profile) #### Parameters | | | | | --- | --- | --- | | Profile | $profile | | ### leave(Profile $profile) #### Parameters | | | | | --- | --- | --- | | Profile | $profile | | ### getName() {@inheritdoc} symfony CodeExtension CodeExtension ============== class **CodeExtension** extends AbstractExtension Twig extension relate to PHP code and used by the profiler and the default exception templates. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string|[FileLinkFormatter](../../../component/httpkernel/debug/filelinkformatter "Symfony\Component\HttpKernel\Debug\FileLinkFormatter") $fileLinkFormat, string $rootDir, string $charset) | | | | [getFilters](#method_getFilters)() {@inheritdoc} | | | | [abbrClass](#method_abbrClass)($class) | | | | [abbrMethod](#method_abbrMethod)($method) | | | string | [formatArgs](#method_formatArgs)(array $args) Formats an array as a string. | | | string | [formatArgsAsText](#method_formatArgsAsText)(array $args) Formats an array as a string. | | | string | [fileExcerpt](#method_fileExcerpt)(string $file, int $line, int $srcContext = 3) Returns an excerpt of a code file around the given line number. | | | string | [formatFile](#method_formatFile)(string $file, int $line, string $text = null) Formats a file path. | | | string|false | [getFileLink](#method_getFileLink)(string $file, int $line) Returns the link for a given file/line pair. | | | | [formatFileFromText](#method_formatFileFromText)($text) | | | | [formatLogMessage](#method_formatLogMessage)($message, array $context) | | | | [getName](#method_getName)() {@inheritdoc} | | | static | [fixCodeMarkup](#method_fixCodeMarkup)($line) | | Details ------- ### \_\_construct(string|[FileLinkFormatter](../../../component/httpkernel/debug/filelinkformatter "Symfony\Component\HttpKernel\Debug\FileLinkFormatter") $fileLinkFormat, string $rootDir, string $charset) #### Parameters | | | | | --- | --- | --- | | string|[FileLinkFormatter](../../../component/httpkernel/debug/filelinkformatter "Symfony\Component\HttpKernel\Debug\FileLinkFormatter") | $fileLinkFormat | The format for links to source files | | string | $rootDir | The project root directory | | string | $charset | The charset | ### getFilters() {@inheritdoc} ### abbrClass($class) #### Parameters | | | | | --- | --- | --- | | | $class | | ### abbrMethod($method) #### Parameters | | | | | --- | --- | --- | | | $method | | ### string formatArgs(array $args) Formats an array as a string. #### Parameters | | | | | --- | --- | --- | | array | $args | The argument array | #### Return Value | | | | --- | --- | | string | | ### string formatArgsAsText(array $args) Formats an array as a string. #### Parameters | | | | | --- | --- | --- | | array | $args | The argument array | #### Return Value | | | | --- | --- | | string | | ### string fileExcerpt(string $file, int $line, int $srcContext = 3) Returns an excerpt of a code file around the given line number. #### Parameters | | | | | --- | --- | --- | | string | $file | A file path | | int | $line | The selected line number | | int | $srcContext | The number of displayed lines around or -1 for the whole file | #### Return Value | | | | --- | --- | | string | An HTML string | ### string formatFile(string $file, int $line, string $text = null) Formats a file path. #### Parameters | | | | | --- | --- | --- | | string | $file | An absolute file path | | int | $line | The line number | | string | $text | Use this text for the link rather than the file path | #### Return Value | | | | --- | --- | | string | | ### string|false getFileLink(string $file, int $line) Returns the link for a given file/line pair. #### Parameters | | | | | --- | --- | --- | | string | $file | An absolute file path | | int | $line | The line number | #### Return Value | | | | --- | --- | | string|false | A link or false | ### formatFileFromText($text) #### Parameters | | | | | --- | --- | --- | | | $text | | ### formatLogMessage($message, array $context) #### Parameters | | | | | --- | --- | --- | | | $message | | | array | $context | | ### getName() {@inheritdoc} ### static protected fixCodeMarkup($line) #### Parameters | | | | | --- | --- | --- | | | $line | |
programming_docs
symfony YamlExtension YamlExtension ============== class **YamlExtension** extends AbstractExtension Provides integration of the Yaml component with Twig. Methods ------- | | | | | --- | --- | --- | | | [getFilters](#method_getFilters)() {@inheritdoc} | | | | [encode](#method_encode)($input, $inline = 0, $dumpObjects = 0) | | | | [dump](#method_dump)($value, $inline = 0, $dumpObjects = false) | | | | [getName](#method_getName)() {@inheritdoc} | | Details ------- ### getFilters() {@inheritdoc} ### encode($input, $inline = 0, $dumpObjects = 0) #### Parameters | | | | | --- | --- | --- | | | $input | | | | $inline | | | | $dumpObjects | | ### dump($value, $inline = 0, $dumpObjects = false) #### Parameters | | | | | --- | --- | --- | | | $value | | | | $inline | | | | $dumpObjects | | ### getName() {@inheritdoc} symfony HttpFoundationExtension HttpFoundationExtension ======================== class **HttpFoundationExtension** extends AbstractExtension Twig extension for the Symfony HttpFoundation component. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([RequestStack](../../../component/httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack, [RequestContext](../../../component/routing/requestcontext "Symfony\Component\Routing\RequestContext") $requestContext = null) | | | | [getFunctions](#method_getFunctions)() {@inheritdoc} | | | string | [generateAbsoluteUrl](#method_generateAbsoluteUrl)(string $path) Returns the absolute URL for the given absolute or relative path. | | | string | [generateRelativePath](#method_generateRelativePath)(string $path) Returns a relative path based on the current Request. | | | string | [getName](#method_getName)() Returns the name of the extension. | | Details ------- ### \_\_construct([RequestStack](../../../component/httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack, [RequestContext](../../../component/routing/requestcontext "Symfony\Component\Routing\RequestContext") $requestContext = null) #### Parameters | | | | | --- | --- | --- | | [RequestStack](../../../component/httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") | $requestStack | | | [RequestContext](../../../component/routing/requestcontext "Symfony\Component\Routing\RequestContext") | $requestContext | | ### getFunctions() {@inheritdoc} ### string generateAbsoluteUrl(string $path) Returns the absolute URL for the given absolute or relative path. This method returns the path unchanged if no request is available. #### Parameters | | | | | --- | --- | --- | | string | $path | The path | #### Return Value | | | | --- | --- | | string | The absolute URL | #### See also | | | | --- | --- | | [Request::getUriForPath](../../../component/httpfoundation/request#method_getUriForPath "Symfony\Component\HttpFoundation\Request") | | ### string generateRelativePath(string $path) Returns a relative path based on the current Request. This method returns the path unchanged if no request is available. #### Parameters | | | | | --- | --- | --- | | string | $path | The path | #### Return Value | | | | --- | --- | | string | The relative path | #### See also | | | | --- | --- | | [Request::getRelativeUriForPath](../../../component/httpfoundation/request#method_getRelativeUriForPath "Symfony\Component\HttpFoundation\Request") | | ### string getName() Returns the name of the extension. #### Return Value | | | | --- | --- | | string | The extension name | symfony FormExtension FormExtension ============== class **FormExtension** extends AbstractExtension FormExtension extends Twig with form capabilities. Methods ------- | | | | | --- | --- | --- | | | [getTokenParsers](#method_getTokenParsers)() {@inheritdoc} | | | | [getFunctions](#method_getFunctions)() {@inheritdoc} | | | | [getFilters](#method_getFilters)() {@inheritdoc} | | | | [getTests](#method_getTests)() {@inheritdoc} | | | | [getName](#method_getName)() {@inheritdoc} | | Details ------- ### getTokenParsers() {@inheritdoc} ### getFunctions() {@inheritdoc} ### getFilters() {@inheritdoc} ### getTests() {@inheritdoc} ### getName() {@inheritdoc} symfony AssetExtension AssetExtension =============== class **AssetExtension** extends AbstractExtension Twig extension for the Symfony Asset component. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([Packages](../../../component/asset/packages "Symfony\Component\Asset\Packages") $packages) | | | | [getFunctions](#method_getFunctions)() {@inheritdoc} | | | string | [getAssetUrl](#method_getAssetUrl)(string $path, string $packageName = null) Returns the public url/path of an asset. | | | string | [getAssetVersion](#method_getAssetVersion)(string $path, string $packageName = null) Returns the version of an asset. | | | string | [getName](#method_getName)() Returns the name of the extension. | | Details ------- ### \_\_construct([Packages](../../../component/asset/packages "Symfony\Component\Asset\Packages") $packages) #### Parameters | | | | | --- | --- | --- | | [Packages](../../../component/asset/packages "Symfony\Component\Asset\Packages") | $packages | | ### getFunctions() {@inheritdoc} ### string getAssetUrl(string $path, string $packageName = null) Returns the public url/path of an asset. If the package used to generate the path is an instance of UrlPackage, you will always get a URL and not a path. #### Parameters | | | | | --- | --- | --- | | string | $path | A public path | | string | $packageName | The name of the asset package to use | #### Return Value | | | | --- | --- | | string | The public path of the asset | ### string getAssetVersion(string $path, string $packageName = null) Returns the version of an asset. #### Parameters | | | | | --- | --- | --- | | string | $path | A public path | | string | $packageName | The name of the asset package to use | #### Return Value | | | | --- | --- | | string | The asset version | ### string getName() Returns the name of the extension. #### Return Value | | | | --- | --- | | string | The extension name | symfony HttpKernelExtension HttpKernelExtension ==================== class **HttpKernelExtension** extends AbstractExtension Provides integration with the HttpKernel component. Methods ------- | | | | | --- | --- | --- | | | [getFunctions](#method_getFunctions)() | | | static | [controller](#method_controller)($controller, $attributes = array(), $query = array()) | | | | [getName](#method_getName)() {@inheritdoc} | | Details ------- ### getFunctions() ### static controller($controller, $attributes = array(), $query = array()) #### Parameters | | | | | --- | --- | --- | | | $controller | | | | $attributes | | | | $query | | ### getName() {@inheritdoc} symfony ExpressionExtension ExpressionExtension ==================== class **ExpressionExtension** extends AbstractExtension ExpressionExtension gives a way to create Expressions from a template. Methods ------- | | | | | --- | --- | --- | | | [getFunctions](#method_getFunctions)() {@inheritdoc} | | | | [createExpression](#method_createExpression)($expression) | | | string | [getName](#method_getName)() Returns the name of the extension. | | Details ------- ### getFunctions() {@inheritdoc} ### createExpression($expression) #### Parameters | | | | | --- | --- | --- | | | $expression | | ### string getName() Returns the name of the extension. #### Return Value | | | | --- | --- | | string | The extension name | symfony LogoutUrlExtension LogoutUrlExtension =================== class **LogoutUrlExtension** extends AbstractExtension LogoutUrlHelper provides generator functions for the logout URL to Twig. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([LogoutUrlGenerator](../../../component/security/http/logout/logouturlgenerator "Symfony\Component\Security\Http\Logout\LogoutUrlGenerator") $generator) | | | | [getFunctions](#method_getFunctions)() {@inheritdoc} | | | string | [getLogoutPath](#method_getLogoutPath)(string|null $key = null) Generates the relative logout URL for the firewall. | | | string | [getLogoutUrl](#method_getLogoutUrl)(string|null $key = null) Generates the absolute logout URL for the firewall. | | | | [getName](#method_getName)() {@inheritdoc} | | Details ------- ### \_\_construct([LogoutUrlGenerator](../../../component/security/http/logout/logouturlgenerator "Symfony\Component\Security\Http\Logout\LogoutUrlGenerator") $generator) #### Parameters | | | | | --- | --- | --- | | [LogoutUrlGenerator](../../../component/security/http/logout/logouturlgenerator "Symfony\Component\Security\Http\Logout\LogoutUrlGenerator") | $generator | | ### getFunctions() {@inheritdoc} ### string getLogoutPath(string|null $key = null) Generates the relative logout URL for the firewall. #### Parameters | | | | | --- | --- | --- | | string|null | $key | The firewall key or null to use the current firewall key | #### Return Value | | | | --- | --- | | string | The relative logout URL | ### string getLogoutUrl(string|null $key = null) Generates the absolute logout URL for the firewall. #### Parameters | | | | | --- | --- | --- | | string|null | $key | The firewall key or null to use the current firewall key | #### Return Value | | | | --- | --- | | string | The absolute logout URL | ### getName() {@inheritdoc} symfony CsrfRuntime CsrfRuntime ============ class **CsrfRuntime** Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([CsrfTokenManagerInterface](../../../component/security/csrf/csrftokenmanagerinterface "Symfony\Component\Security\Csrf\CsrfTokenManagerInterface") $csrfTokenManager) | | | string | [getCsrfToken](#method_getCsrfToken)(string $tokenId) | | Details ------- ### \_\_construct([CsrfTokenManagerInterface](../../../component/security/csrf/csrftokenmanagerinterface "Symfony\Component\Security\Csrf\CsrfTokenManagerInterface") $csrfTokenManager) #### Parameters | | | | | --- | --- | --- | | [CsrfTokenManagerInterface](../../../component/security/csrf/csrftokenmanagerinterface "Symfony\Component\Security\Csrf\CsrfTokenManagerInterface") | $csrfTokenManager | | ### string getCsrfToken(string $tokenId) #### Parameters | | | | | --- | --- | --- | | string | $tokenId | | #### Return Value | | | | --- | --- | | string | | symfony WebLinkExtension WebLinkExtension ================= class **WebLinkExtension** extends AbstractExtension Twig extension for the Symfony WebLink component. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([RequestStack](../../../component/httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack) | | | | [getFunctions](#method_getFunctions)() {@inheritdoc} | | | string | [link](#method_link)(string $uri, string $rel, array $attributes = array()) Adds a "Link" HTTP header. | | | string | [preload](#method_preload)(string $uri, array $attributes = array()) Preloads a resource. | | | string | [dnsPrefetch](#method_dnsPrefetch)(string $uri, array $attributes = array()) Resolves a resource origin as early as possible. | | | string | [preconnect](#method_preconnect)(string $uri, array $attributes = array()) Initiates a early connection to a resource (DNS resolution, TCP handshake, TLS negotiation). | | | string | [prefetch](#method_prefetch)(string $uri, array $attributes = array()) Indicates to the client that it should prefetch this resource. | | | string | [prerender](#method_prerender)(string $uri, array $attributes = array()) Indicates to the client that it should prerender this resource . | | Details ------- ### \_\_construct([RequestStack](../../../component/httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack) #### Parameters | | | | | --- | --- | --- | | [RequestStack](../../../component/httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") | $requestStack | | ### getFunctions() {@inheritdoc} ### string link(string $uri, string $rel, array $attributes = array()) Adds a "Link" HTTP header. #### Parameters | | | | | --- | --- | --- | | string | $uri | The relation URI | | string | $rel | The relation type (e.g. "preload", "prefetch", "prerender" or "dns-prefetch") | | array | $attributes | The attributes of this link (e.g. "array('as' => true)", "array('pr' => 0.5)") | #### Return Value | | | | --- | --- | | string | The relation URI | ### string preload(string $uri, array $attributes = array()) Preloads a resource. #### Parameters | | | | | --- | --- | --- | | string | $uri | A public path | | array | $attributes | The attributes of this link (e.g. "array('as' => true)", "array('crossorigin' => 'use-credentials')") | #### Return Value | | | | --- | --- | | string | The path of the asset | ### string dnsPrefetch(string $uri, array $attributes = array()) Resolves a resource origin as early as possible. #### Parameters | | | | | --- | --- | --- | | string | $uri | A public path | | array | $attributes | The attributes of this link (e.g. "array('as' => true)", "array('pr' => 0.5)") | #### Return Value | | | | --- | --- | | string | The path of the asset | ### string preconnect(string $uri, array $attributes = array()) Initiates a early connection to a resource (DNS resolution, TCP handshake, TLS negotiation). #### Parameters | | | | | --- | --- | --- | | string | $uri | A public path | | array | $attributes | The attributes of this link (e.g. "array('as' => true)", "array('pr' => 0.5)") | #### Return Value | | | | --- | --- | | string | The path of the asset | ### string prefetch(string $uri, array $attributes = array()) Indicates to the client that it should prefetch this resource. #### Parameters | | | | | --- | --- | --- | | string | $uri | A public path | | array | $attributes | The attributes of this link (e.g. "array('as' => true)", "array('pr' => 0.5)") | #### Return Value | | | | --- | --- | | string | The path of the asset | ### string prerender(string $uri, array $attributes = array()) Indicates to the client that it should prerender this resource . #### Parameters | | | | | --- | --- | --- | | string | $uri | A public path | | array | $attributes | The attributes of this link (e.g. "array('as' => true)", "array('pr' => 0.5)") | #### Return Value | | | | --- | --- | | string | The path of the asset | symfony HttpKernelRuntime HttpKernelRuntime ================== class **HttpKernelRuntime** Provides integration with the HttpKernel component. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([FragmentHandler](../../../component/httpkernel/fragment/fragmenthandler "Symfony\Component\HttpKernel\Fragment\FragmentHandler") $handler) | | | string | [renderFragment](#method_renderFragment)(string|[ControllerReference](../../../component/httpkernel/controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $uri, array $options = array()) Renders a fragment. | | | string | [renderFragmentStrategy](#method_renderFragmentStrategy)(string $strategy, string|[ControllerReference](../../../component/httpkernel/controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $uri, array $options = array()) Renders a fragment. | | Details ------- ### \_\_construct([FragmentHandler](../../../component/httpkernel/fragment/fragmenthandler "Symfony\Component\HttpKernel\Fragment\FragmentHandler") $handler) #### Parameters | | | | | --- | --- | --- | | [FragmentHandler](../../../component/httpkernel/fragment/fragmenthandler "Symfony\Component\HttpKernel\Fragment\FragmentHandler") | $handler | | ### string renderFragment(string|[ControllerReference](../../../component/httpkernel/controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $uri, array $options = array()) Renders a fragment. #### Parameters | | | | | --- | --- | --- | | string|[ControllerReference](../../../component/httpkernel/controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") | $uri | A URI as a string or a ControllerReference instance | | array | $options | An array of options | #### Return Value | | | | --- | --- | | string | The fragment content | #### See also | | | | --- | --- | | [FragmentHandler::render](../../../component/httpkernel/fragment/fragmenthandler#method_render "Symfony\Component\HttpKernel\Fragment\FragmentHandler") | | ### string renderFragmentStrategy(string $strategy, string|[ControllerReference](../../../component/httpkernel/controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $uri, array $options = array()) Renders a fragment. #### Parameters | | | | | --- | --- | --- | | string | $strategy | A strategy name | | string|[ControllerReference](../../../component/httpkernel/controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") | $uri | A URI as a string or a ControllerReference instance | | array | $options | An array of options | #### Return Value | | | | --- | --- | | string | The fragment content | #### See also | | | | --- | --- | | [FragmentHandler::render](../../../component/httpkernel/fragment/fragmenthandler#method_render "Symfony\Component\HttpKernel\Fragment\FragmentHandler") | | symfony CsrfExtension CsrfExtension ============== class **CsrfExtension** extends AbstractExtension Methods ------- | | | | | --- | --- | --- | | array | [getFunctions](#method_getFunctions)() {@inheritdoc} | | Details ------- ### array getFunctions() {@inheritdoc} #### Return Value | | | | --- | --- | | array | | symfony RoutingExtension RoutingExtension ================= class **RoutingExtension** extends AbstractExtension Provides integration of the Routing component with Twig. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([UrlGeneratorInterface](../../../component/routing/generator/urlgeneratorinterface "Symfony\Component\Routing\Generator\UrlGeneratorInterface") $generator) | | | array | [getFunctions](#method_getFunctions)() Returns a list of functions to add to the existing list. | | | string | [getPath](#method_getPath)(string $name, array $parameters = array(), bool $relative = false) | | | string | [getUrl](#method_getUrl)(string $name, array $parameters = array(), bool $schemeRelative = false) | | | array | [isUrlGenerationSafe](#method_isUrlGenerationSafe)(Node $argsNode) Determines at compile time whether the generated URL will be safe and thus saving the unneeded automatic escaping for performance reasons. | | | | [getName](#method_getName)() {@inheritdoc} | | Details ------- ### \_\_construct([UrlGeneratorInterface](../../../component/routing/generator/urlgeneratorinterface "Symfony\Component\Routing\Generator\UrlGeneratorInterface") $generator) #### Parameters | | | | | --- | --- | --- | | [UrlGeneratorInterface](../../../component/routing/generator/urlgeneratorinterface "Symfony\Component\Routing\Generator\UrlGeneratorInterface") | $generator | | ### array getFunctions() Returns a list of functions to add to the existing list. #### Return Value | | | | --- | --- | | array | An array of functions | ### string getPath(string $name, array $parameters = array(), bool $relative = false) #### Parameters | | | | | --- | --- | --- | | string | $name | | | array | $parameters | | | bool | $relative | | #### Return Value | | | | --- | --- | | string | | ### string getUrl(string $name, array $parameters = array(), bool $schemeRelative = false) #### Parameters | | | | | --- | --- | --- | | string | $name | | | array | $parameters | | | bool | $schemeRelative | | #### Return Value | | | | --- | --- | | string | | ### array isUrlGenerationSafe(Node $argsNode) Determines at compile time whether the generated URL will be safe and thus saving the unneeded automatic escaping for performance reasons. The URL generation process percent encodes non-alphanumeric characters. So there is no risk that malicious/invalid characters are part of the URL. The only character within an URL that must be escaped in html is the ampersand ("&") which separates query params. So we cannot mark the URL generation as always safe, but only when we are sure there won't be multiple query params. This is the case when there are none or only one constant parameter given. E.g. we know beforehand this will be safe: - path('route') - path('route', {'param': 'value'}) But the following may not: - path('route', var) - path('route', {'param': ['val1', 'val2'] }) // a sub-array - path('route', {'param1': 'value1', 'param2': 'value2'}) If param1 and param2 reference placeholder in the route, it would still be safe. But we don't know. #### Parameters | | | | | --- | --- | --- | | Node | $argsNode | The arguments of the path/url function | #### Return Value | | | | --- | --- | | array | An array with the contexts the URL is safe | ### getName() {@inheritdoc}
programming_docs
symfony DumpExtension DumpExtension ============== class **DumpExtension** extends AbstractExtension Provides integration of the dump() function with Twig. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([ClonerInterface](../../../component/vardumper/cloner/clonerinterface "Symfony\Component\VarDumper\Cloner\ClonerInterface") $cloner, [HtmlDumper](../../../component/vardumper/dumper/htmldumper "Symfony\Component\VarDumper\Dumper\HtmlDumper") $dumper = null) | | | | [getFunctions](#method_getFunctions)() | | | | [getTokenParsers](#method_getTokenParsers)() | | | | [getName](#method_getName)() | | | | [dump](#method_dump)(Environment $env, $context) | | Details ------- ### \_\_construct([ClonerInterface](../../../component/vardumper/cloner/clonerinterface "Symfony\Component\VarDumper\Cloner\ClonerInterface") $cloner, [HtmlDumper](../../../component/vardumper/dumper/htmldumper "Symfony\Component\VarDumper\Dumper\HtmlDumper") $dumper = null) #### Parameters | | | | | --- | --- | --- | | [ClonerInterface](../../../component/vardumper/cloner/clonerinterface "Symfony\Component\VarDumper\Cloner\ClonerInterface") | $cloner | | | [HtmlDumper](../../../component/vardumper/dumper/htmldumper "Symfony\Component\VarDumper\Dumper\HtmlDumper") | $dumper | | ### getFunctions() ### getTokenParsers() ### getName() ### dump(Environment $env, $context) #### Parameters | | | | | --- | --- | --- | | Environment | $env | | | | $context | | symfony TranslationExtension TranslationExtension ===================== class **TranslationExtension** extends AbstractExtension Provides integration of the Translation component with Twig. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([TranslatorInterface](../../../component/translation/translatorinterface "Symfony\Component\Translation\TranslatorInterface") $translator = null, NodeVisitorInterface $translationNodeVisitor = null) | | | | [getTranslator](#method_getTranslator)() | | | | [getFilters](#method_getFilters)() {@inheritdoc} | | | AbstractTokenParser[] | [getTokenParsers](#method_getTokenParsers)() Returns the token parser instance to add to the existing list. | | | | [getNodeVisitors](#method_getNodeVisitors)() {@inheritdoc} | | | | [getTranslationNodeVisitor](#method_getTranslationNodeVisitor)() | | | | [trans](#method_trans)($message, array $arguments = array(), $domain = null, $locale = null) | | | | [transchoice](#method_transchoice)($message, $count, array $arguments = array(), $domain = null, $locale = null) | | | | [getName](#method_getName)() {@inheritdoc} | | Details ------- ### \_\_construct([TranslatorInterface](../../../component/translation/translatorinterface "Symfony\Component\Translation\TranslatorInterface") $translator = null, NodeVisitorInterface $translationNodeVisitor = null) #### Parameters | | | | | --- | --- | --- | | [TranslatorInterface](../../../component/translation/translatorinterface "Symfony\Component\Translation\TranslatorInterface") | $translator | | | NodeVisitorInterface | $translationNodeVisitor | | ### getTranslator() ### getFilters() {@inheritdoc} ### AbstractTokenParser[] getTokenParsers() Returns the token parser instance to add to the existing list. #### Return Value | | | | --- | --- | | AbstractTokenParser[] | | ### getNodeVisitors() {@inheritdoc} ### getTranslationNodeVisitor() ### trans($message, array $arguments = array(), $domain = null, $locale = null) #### Parameters | | | | | --- | --- | --- | | | $message | | | array | $arguments | | | | $domain | | | | $locale | | ### transchoice($message, $count, array $arguments = array(), $domain = null, $locale = null) #### Parameters | | | | | --- | --- | --- | | | $message | | | | $count | | | array | $arguments | | | | $domain | | | | $locale | | ### getName() {@inheritdoc} symfony TranslationDefaultDomainNodeVisitor TranslationDefaultDomainNodeVisitor ==================================== class **TranslationDefaultDomainNodeVisitor** extends AbstractNodeVisitor Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)() | | | | [doEnterNode](#method_doEnterNode)(Node $node, Environment $env) {@inheritdoc} | | | | [doLeaveNode](#method_doLeaveNode)(Node $node, Environment $env) {@inheritdoc} | | | | [getPriority](#method_getPriority)() {@inheritdoc} | | Details ------- ### \_\_construct() ### protected doEnterNode(Node $node, Environment $env) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | Node | $node | | | Environment | $env | | ### protected doLeaveNode(Node $node, Environment $env) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | Node | $node | | | Environment | $env | | ### getPriority() {@inheritdoc} symfony TranslationNodeVisitor TranslationNodeVisitor ======================= class **TranslationNodeVisitor** extends AbstractNodeVisitor TranslationNodeVisitor extracts translation messages. Constants --------- | | | | --- | --- | | UNDEFINED\_DOMAIN | | Methods ------- | | | | | --- | --- | --- | | | [enable](#method_enable)() | | | | [disable](#method_disable)() | | | | [getMessages](#method_getMessages)() | | | | [doEnterNode](#method_doEnterNode)(Node $node, Environment $env) {@inheritdoc} | | | | [doLeaveNode](#method_doLeaveNode)(Node $node, Environment $env) {@inheritdoc} | | | | [getPriority](#method_getPriority)() {@inheritdoc} | | Details ------- ### enable() ### disable() ### getMessages() ### protected doEnterNode(Node $node, Environment $env) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | Node | $node | | | Environment | $env | | ### protected doLeaveNode(Node $node, Environment $env) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | Node | $node | | | Environment | $env | | ### getPriority() {@inheritdoc} symfony Scope Scope ====== class **Scope** Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([Scope](scope "Symfony\Bridge\Twig\NodeVisitor\Scope") $parent = null) | | | [Scope](scope "Symfony\Bridge\Twig\NodeVisitor\Scope") | [enter](#method_enter)() Opens a new child scope. | | | [Scope](scope "Symfony\Bridge\Twig\NodeVisitor\Scope")|null | [leave](#method_leave)() Closes current scope and returns parent one. | | | $this | [set](#method_set)(string $key, mixed $value) Stores data into current scope. | | | bool | [has](#method_has)(string $key) Tests if a data is visible from current scope. | | | mixed | [get](#method_get)(string $key, mixed $default = null) Returns data visible from current scope. | | Details ------- ### \_\_construct([Scope](scope "Symfony\Bridge\Twig\NodeVisitor\Scope") $parent = null) #### Parameters | | | | | --- | --- | --- | | [Scope](scope "Symfony\Bridge\Twig\NodeVisitor\Scope") | $parent | | ### [Scope](scope "Symfony\Bridge\Twig\NodeVisitor\Scope") enter() Opens a new child scope. #### Return Value | | | | --- | --- | | [Scope](scope "Symfony\Bridge\Twig\NodeVisitor\Scope") | | ### [Scope](scope "Symfony\Bridge\Twig\NodeVisitor\Scope")|null leave() Closes current scope and returns parent one. #### Return Value | | | | --- | --- | | [Scope](scope "Symfony\Bridge\Twig\NodeVisitor\Scope")|null | | ### $this set(string $key, mixed $value) Stores data into current scope. #### Parameters | | | | | --- | --- | --- | | string | $key | | | mixed | $value | | #### Return Value | | | | --- | --- | | $this | | #### Exceptions | | | | --- | --- | | [LogicException](http://php.net/LogicException) | | ### bool has(string $key) Tests if a data is visible from current scope. #### Parameters | | | | | --- | --- | --- | | string | $key | | #### Return Value | | | | --- | --- | | bool | | ### mixed get(string $key, mixed $default = null) Returns data visible from current scope. #### Parameters | | | | | --- | --- | --- | | string | $key | | | mixed | $default | | #### Return Value | | | | --- | --- | | mixed | | symfony TwigExtractor TwigExtractor ============== class **TwigExtractor** extends [AbstractFileExtractor](../../../component/translation/extractor/abstractfileextractor "Symfony\Component\Translation\Extractor\AbstractFileExtractor") implements [ExtractorInterface](../../../component/translation/extractor/extractorinterface "Symfony\Component\Translation\Extractor\ExtractorInterface") TwigExtractor extracts translation messages from a twig template. Methods ------- | | | | | --- | --- | --- | | array | [extractFiles](#method_extractFiles)(string|array $resource) | from [AbstractFileExtractor](../../../component/translation/extractor/abstractfileextractor#method_extractFiles "Symfony\Component\Translation\Extractor\AbstractFileExtractor") | | bool | [isFile](#method_isFile)(string $file) | from [AbstractFileExtractor](../../../component/translation/extractor/abstractfileextractor#method_isFile "Symfony\Component\Translation\Extractor\AbstractFileExtractor") | | bool | [canBeExtracted](#method_canBeExtracted)(string $file) | | | array | [extractFromDirectory](#method_extractFromDirectory)(string|array $directory) | | | | [\_\_construct](#method___construct)(Environment $twig) | | | | [extract](#method_extract)(string|array $resource, [MessageCatalogue](../../../component/translation/messagecatalogue "Symfony\Component\Translation\MessageCatalogue") $catalogue) Extracts translation messages from files, a file or a directory to the catalogue. | | | | [setPrefix](#method_setPrefix)(string $prefix) Sets the prefix that should be used for new found messages. | | | | [extractTemplate](#method_extractTemplate)($template, [MessageCatalogue](../../../component/translation/messagecatalogue "Symfony\Component\Translation\MessageCatalogue") $catalogue) | | Details ------- ### protected array extractFiles(string|array $resource) #### Parameters | | | | | --- | --- | --- | | string|array | $resource | Files, a file or a directory | #### Return Value | | | | --- | --- | | array | | ### protected bool isFile(string $file) #### Parameters | | | | | --- | --- | --- | | string | $file | | #### Return Value | | | | --- | --- | | bool | | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](../../../component/translation/exception/invalidargumentexception "Symfony\Component\Translation\Exception\InvalidArgumentException") | | ### protected bool canBeExtracted(string $file) #### Parameters | | | | | --- | --- | --- | | string | $file | | #### Return Value | | | | --- | --- | | bool | | ### protected array extractFromDirectory(string|array $directory) #### Parameters | | | | | --- | --- | --- | | string|array | $directory | | #### Return Value | | | | --- | --- | | array | files to be extracted | ### \_\_construct(Environment $twig) #### Parameters | | | | | --- | --- | --- | | Environment | $twig | | ### extract(string|array $resource, [MessageCatalogue](../../../component/translation/messagecatalogue "Symfony\Component\Translation\MessageCatalogue") $catalogue) Extracts translation messages from files, a file or a directory to the catalogue. #### Parameters | | | | | --- | --- | --- | | string|array | $resource | Files, a file or a directory | | [MessageCatalogue](../../../component/translation/messagecatalogue "Symfony\Component\Translation\MessageCatalogue") | $catalogue | The catalogue | ### setPrefix(string $prefix) Sets the prefix that should be used for new found messages. #### Parameters | | | | | --- | --- | --- | | string | $prefix | The prefix | ### protected extractTemplate($template, [MessageCatalogue](../../../component/translation/messagecatalogue "Symfony\Component\Translation\MessageCatalogue") $catalogue) #### Parameters | | | | | --- | --- | --- | | | $template | | | [MessageCatalogue](../../../component/translation/messagecatalogue "Symfony\Component\Translation\MessageCatalogue") | $catalogue | | symfony DebugCommand DebugCommand ============= class **DebugCommand** extends [Command](../../../component/console/command/command "Symfony\Component\Console\Command\Command") Lists twig functions, filters, globals and tests present in the current project. Properties ---------- | | | | | | --- | --- | --- | --- | | static protected | $defaultName | | | Methods ------- | | | | | --- | --- | --- | | static string|null | [getDefaultName](#method_getDefaultName)() | from [Command](../../../component/console/command/command#method_getDefaultName "Symfony\Component\Console\Command\Command") | | | [\_\_construct](#method___construct)(Environment $twig, string $projectDir = null) | | | | [ignoreValidationErrors](#method_ignoreValidationErrors)() Ignores validation errors. | from [Command](../../../component/console/command/command#method_ignoreValidationErrors "Symfony\Component\Console\Command\Command") | | | [setApplication](#method_setApplication)([Application](../../../component/console/application "Symfony\Component\Console\Application") $application = null) | from [Command](../../../component/console/command/command#method_setApplication "Symfony\Component\Console\Command\Command") | | | [setHelperSet](#method_setHelperSet)([HelperSet](../../../component/console/helper/helperset "Symfony\Component\Console\Helper\HelperSet") $helperSet) | from [Command](../../../component/console/command/command#method_setHelperSet "Symfony\Component\Console\Command\Command") | | [HelperSet](../../../component/console/helper/helperset "Symfony\Component\Console\Helper\HelperSet") | [getHelperSet](#method_getHelperSet)() Gets the helper set. | from [Command](../../../component/console/command/command#method_getHelperSet "Symfony\Component\Console\Command\Command") | | [Application](../../../component/console/application "Symfony\Component\Console\Application") | [getApplication](#method_getApplication)() Gets the application instance for this command. | from [Command](../../../component/console/command/command#method_getApplication "Symfony\Component\Console\Command\Command") | | bool | [isEnabled](#method_isEnabled)() Checks whether the command is enabled or not in the current environment. | from [Command](../../../component/console/command/command#method_isEnabled "Symfony\Component\Console\Command\Command") | | | [configure](#method_configure)() Configures the current command. | | | int|null | [execute](#method_execute)([InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") $input, [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") $output) Executes the current command. | | | | [interact](#method_interact)([InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") $input, [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") $output) Interacts with the user. | from [Command](../../../component/console/command/command#method_interact "Symfony\Component\Console\Command\Command") | | | [initialize](#method_initialize)([InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") $input, [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") $output) Initializes the command after the input has been bound and before the input is validated. | from [Command](../../../component/console/command/command#method_initialize "Symfony\Component\Console\Command\Command") | | int | [run](#method_run)([InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") $input, [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") $output) Runs the command. | from [Command](../../../component/console/command/command#method_run "Symfony\Component\Console\Command\Command") | | $this | [setCode](#method_setCode)(callable $code) Sets the code to execute when running this command. | from [Command](../../../component/console/command/command#method_setCode "Symfony\Component\Console\Command\Command") | | | [mergeApplicationDefinition](#method_mergeApplicationDefinition)(bool $mergeArgs = true) Merges the application definition with the command definition. | from [Command](../../../component/console/command/command#method_mergeApplicationDefinition "Symfony\Component\Console\Command\Command") | | $this | [setDefinition](#method_setDefinition)(array|[InputDefinition](../../../component/console/input/inputdefinition "Symfony\Component\Console\Input\InputDefinition") $definition) Sets an array of argument and option instances. | from [Command](../../../component/console/command/command#method_setDefinition "Symfony\Component\Console\Command\Command") | | [InputDefinition](../../../component/console/input/inputdefinition "Symfony\Component\Console\Input\InputDefinition") | [getDefinition](#method_getDefinition)() Gets the InputDefinition attached to this Command. | from [Command](../../../component/console/command/command#method_getDefinition "Symfony\Component\Console\Command\Command") | | [InputDefinition](../../../component/console/input/inputdefinition "Symfony\Component\Console\Input\InputDefinition") | [getNativeDefinition](#method_getNativeDefinition)() Gets the InputDefinition to be used to create representations of this Command. | from [Command](../../../component/console/command/command#method_getNativeDefinition "Symfony\Component\Console\Command\Command") | | $this | [addArgument](#method_addArgument)(string $name, int|null $mode = null, string $description = '', string|string[]|null $default = null) Adds an argument. | from [Command](../../../component/console/command/command#method_addArgument "Symfony\Component\Console\Command\Command") | | $this | [addOption](#method_addOption)(string $name, string|array $shortcut = null, int|null $mode = null, string $description = '', string|string[]|bool|null $default = null) Adds an option. | from [Command](../../../component/console/command/command#method_addOption "Symfony\Component\Console\Command\Command") | | $this | [setName](#method_setName)(string $name) Sets the name of the command. | from [Command](../../../component/console/command/command#method_setName "Symfony\Component\Console\Command\Command") | | $this | [setProcessTitle](#method_setProcessTitle)(string $title) Sets the process title of the command. | from [Command](../../../component/console/command/command#method_setProcessTitle "Symfony\Component\Console\Command\Command") | | string | [getName](#method_getName)() Returns the command name. | from [Command](../../../component/console/command/command#method_getName "Symfony\Component\Console\Command\Command") | | [Command](../../../component/console/command/command "Symfony\Component\Console\Command\Command") | [setHidden](#method_setHidden)(bool $hidden) | from [Command](../../../component/console/command/command#method_setHidden "Symfony\Component\Console\Command\Command") | | bool | [isHidden](#method_isHidden)() | from [Command](../../../component/console/command/command#method_isHidden "Symfony\Component\Console\Command\Command") | | $this | [setDescription](#method_setDescription)(string $description) Sets the description for the command. | from [Command](../../../component/console/command/command#method_setDescription "Symfony\Component\Console\Command\Command") | | string | [getDescription](#method_getDescription)() Returns the description for the command. | from [Command](../../../component/console/command/command#method_getDescription "Symfony\Component\Console\Command\Command") | | $this | [setHelp](#method_setHelp)(string $help) Sets the help for the command. | from [Command](../../../component/console/command/command#method_setHelp "Symfony\Component\Console\Command\Command") | | string | [getHelp](#method_getHelp)() Returns the help for the command. | from [Command](../../../component/console/command/command#method_getHelp "Symfony\Component\Console\Command\Command") | | string | [getProcessedHelp](#method_getProcessedHelp)() Returns the processed help for the command replacing the %command.name% and %command.full\_name% patterns with the real values dynamically. | from [Command](../../../component/console/command/command#method_getProcessedHelp "Symfony\Component\Console\Command\Command") | | $this | [setAliases](#method_setAliases)(string[] $aliases) Sets the aliases for the command. | from [Command](../../../component/console/command/command#method_setAliases "Symfony\Component\Console\Command\Command") | | array | [getAliases](#method_getAliases)() Returns the aliases for the command. | from [Command](../../../component/console/command/command#method_getAliases "Symfony\Component\Console\Command\Command") | | string | [getSynopsis](#method_getSynopsis)(bool $short = false) Returns the synopsis for the command. | from [Command](../../../component/console/command/command#method_getSynopsis "Symfony\Component\Console\Command\Command") | | $this | [addUsage](#method_addUsage)(string $usage) Add a command usage example. | from [Command](../../../component/console/command/command#method_addUsage "Symfony\Component\Console\Command\Command") | | array | [getUsages](#method_getUsages)() Returns alternative usages of the command. | from [Command](../../../component/console/command/command#method_getUsages "Symfony\Component\Console\Command\Command") | | mixed | [getHelper](#method_getHelper)(string $name) Gets a helper instance by name. | from [Command](../../../component/console/command/command#method_getHelper "Symfony\Component\Console\Command\Command") | Details ------- ### static string|null getDefaultName() #### Return Value | | | | --- | --- | | string|null | The default command name or null when no default name is set | ### \_\_construct(Environment $twig, string $projectDir = null) #### Parameters | | | | | --- | --- | --- | | Environment | $twig | | | string | $projectDir | | #### Exceptions | | | | --- | --- | | [LogicException](../../../component/console/exception/logicexception "Symfony\Component\Console\Exception\LogicException") | When the command name is empty | ### ignoreValidationErrors() Ignores validation errors. This is mainly useful for the help command. ### setApplication([Application](../../../component/console/application "Symfony\Component\Console\Application") $application = null) #### Parameters | | | | | --- | --- | --- | | [Application](../../../component/console/application "Symfony\Component\Console\Application") | $application | | ### setHelperSet([HelperSet](../../../component/console/helper/helperset "Symfony\Component\Console\Helper\HelperSet") $helperSet) #### Parameters | | | | | --- | --- | --- | | [HelperSet](../../../component/console/helper/helperset "Symfony\Component\Console\Helper\HelperSet") | $helperSet | | ### [HelperSet](../../../component/console/helper/helperset "Symfony\Component\Console\Helper\HelperSet") getHelperSet() Gets the helper set. #### Return Value | | | | --- | --- | | [HelperSet](../../../component/console/helper/helperset "Symfony\Component\Console\Helper\HelperSet") | A HelperSet instance | ### [Application](../../../component/console/application "Symfony\Component\Console\Application") getApplication() Gets the application instance for this command. #### Return Value | | | | --- | --- | | [Application](../../../component/console/application "Symfony\Component\Console\Application") | An Application instance | ### bool isEnabled() Checks whether the command is enabled or not in the current environment. Override this to check for x or y and return false if the command can not run properly under the current conditions. #### Return Value | | | | --- | --- | | bool | | ### protected configure() Configures the current command. ### protected int|null execute([InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") $input, [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") $output) Executes the current command. This method is not abstract because you can use this class as a concrete class. In this case, instead of defining the execute() method, you set the code to execute by passing a Closure to the setCode() method. #### Parameters | | | | | --- | --- | --- | | [InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") | $input | | | [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") | $output | | #### Return Value | | | | --- | --- | | int|null | null or 0 if everything went fine, or an error code | #### Exceptions | | | | --- | --- | | [LogicException](../../../component/console/exception/logicexception "Symfony\Component\Console\Exception\LogicException") | When this abstract method is not implemented | ### protected interact([InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") $input, [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") $output) Interacts with the user. This method is executed before the InputDefinition is validated. This means that this is the only place where the command can interactively ask for values of missing required arguments. #### Parameters | | | | | --- | --- | --- | | [InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") | $input | | | [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") | $output | | ### protected initialize([InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") $input, [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") $output) Initializes the command after the input has been bound and before the input is validated. This is mainly useful when a lot of commands extends one main command where some things need to be initialized based on the input arguments and options. #### Parameters | | | | | --- | --- | --- | | [InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") | $input | | | [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") | $output | | #### See also | | | | --- | --- | | [InputInterface::bind](../../../component/console/input/inputinterface#method_bind "Symfony\Component\Console\Input\InputInterface") | | | [InputInterface::validate](../../../component/console/input/inputinterface#method_validate "Symfony\Component\Console\Input\InputInterface") | | ### int run([InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") $input, [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") $output) Runs the command. The code to execute is either defined directly with the setCode() method or by overriding the execute() method in a sub-class. #### Parameters | | | | | --- | --- | --- | | [InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") | $input | | | [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") | $output | | #### Return Value | | | | --- | --- | | int | The command exit code | #### Exceptions | | | | --- | --- | | [Exception](http://php.net/Exception) | When binding input fails. Bypass this by calling {@link ignoreValidationErrors()}. | #### See also | | | | --- | --- | | setCode() | | | execute() | | ### $this setCode(callable $code) Sets the code to execute when running this command. If this method is used, it overrides the code defined in the execute() method. #### Parameters | | | | | --- | --- | --- | | callable | $code | A callable(InputInterface $input, OutputInterface $output) | #### Return Value | | | | --- | --- | | $this | | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](../../../component/console/exception/invalidargumentexception "Symfony\Component\Console\Exception\InvalidArgumentException") | | #### See also | | | | --- | --- | | execute() | | ### mergeApplicationDefinition(bool $mergeArgs = true) Merges the application definition with the command definition. This method is not part of public API and should not be used directly. #### Parameters | | | | | --- | --- | --- | | bool | $mergeArgs | Whether to merge or not the Application definition arguments to Command definition arguments | ### $this setDefinition(array|[InputDefinition](../../../component/console/input/inputdefinition "Symfony\Component\Console\Input\InputDefinition") $definition) Sets an array of argument and option instances. #### Parameters | | | | | --- | --- | --- | | array|[InputDefinition](../../../component/console/input/inputdefinition "Symfony\Component\Console\Input\InputDefinition") | $definition | An array of argument and option instances or a definition instance | #### Return Value | | | | --- | --- | | $this | | ### [InputDefinition](../../../component/console/input/inputdefinition "Symfony\Component\Console\Input\InputDefinition") getDefinition() Gets the InputDefinition attached to this Command. #### Return Value | | | | --- | --- | | [InputDefinition](../../../component/console/input/inputdefinition "Symfony\Component\Console\Input\InputDefinition") | An InputDefinition instance | ### [InputDefinition](../../../component/console/input/inputdefinition "Symfony\Component\Console\Input\InputDefinition") getNativeDefinition() Gets the InputDefinition to be used to create representations of this Command. Can be overridden to provide the original command representation when it would otherwise be changed by merging with the application InputDefinition. This method is not part of public API and should not be used directly. #### Return Value | | | | --- | --- | | [InputDefinition](../../../component/console/input/inputdefinition "Symfony\Component\Console\Input\InputDefinition") | An InputDefinition instance | ### $this addArgument(string $name, int|null $mode = null, string $description = '', string|string[]|null $default = null) Adds an argument. #### Parameters | | | | | --- | --- | --- | | string | $name | The argument name | | int|null | $mode | The argument mode: self::REQUIRED or self::OPTIONAL | | string | $description | A description text | | string|string[]|null | $default | The default value (for self::OPTIONAL mode only) | #### Return Value | | | | --- | --- | | $this | | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](../../../component/console/exception/invalidargumentexception "Symfony\Component\Console\Exception\InvalidArgumentException") | When argument mode is not valid | ### $this addOption(string $name, string|array $shortcut = null, int|null $mode = null, string $description = '', string|string[]|bool|null $default = null) Adds an option. #### Parameters | | | | | --- | --- | --- | | string | $name | The option name | | string|array | $shortcut | The shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts | | int|null | $mode | The option mode: One of the VALUE\_\* constants | | string | $description | A description text | | string|string[]|bool|null | $default | The default value (must be null for self::VALUE\_NONE) | #### Return Value | | | | --- | --- | | $this | | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](../../../component/console/exception/invalidargumentexception "Symfony\Component\Console\Exception\InvalidArgumentException") | If option mode is invalid or incompatible | ### $this setName(string $name) Sets the name of the command. This method can set both the namespace and the name if you separate them by a colon (:) ``` $command->setName('foo:bar'); ``` #### Parameters | | | | | --- | --- | --- | | string | $name | The command name | #### Return Value | | | | --- | --- | | $this | | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](../../../component/console/exception/invalidargumentexception "Symfony\Component\Console\Exception\InvalidArgumentException") | When the name is invalid | ### $this setProcessTitle(string $title) Sets the process title of the command. This feature should be used only when creating a long process command, like a daemon. PHP 5.5+ or the proctitle PECL library is required #### Parameters | | | | | --- | --- | --- | | string | $title | The process title | #### Return Value | | | | --- | --- | | $this | | ### string getName() Returns the command name. #### Return Value | | | | --- | --- | | string | The command name | ### [Command](../../../component/console/command/command "Symfony\Component\Console\Command\Command") setHidden(bool $hidden) #### Parameters | | | | | --- | --- | --- | | bool | $hidden | Whether or not the command should be hidden from the list of commands | #### Return Value | | | | --- | --- | | [Command](../../../component/console/command/command "Symfony\Component\Console\Command\Command") | The current instance | ### bool isHidden() #### Return Value | | | | --- | --- | | bool | whether the command should be publicly shown or not | ### $this setDescription(string $description) Sets the description for the command. #### Parameters | | | | | --- | --- | --- | | string | $description | The description for the command | #### Return Value | | | | --- | --- | | $this | | ### string getDescription() Returns the description for the command. #### Return Value | | | | --- | --- | | string | The description for the command | ### $this setHelp(string $help) Sets the help for the command. #### Parameters | | | | | --- | --- | --- | | string | $help | The help for the command | #### Return Value | | | | --- | --- | | $this | | ### string getHelp() Returns the help for the command. #### Return Value | | | | --- | --- | | string | The help for the command | ### string getProcessedHelp() Returns the processed help for the command replacing the %command.name% and %command.full\_name% patterns with the real values dynamically. #### Return Value | | | | --- | --- | | string | The processed help for the command | ### $this setAliases(string[] $aliases) Sets the aliases for the command. #### Parameters | | | | | --- | --- | --- | | string[] | $aliases | An array of aliases for the command | #### Return Value | | | | --- | --- | | $this | | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](../../../component/console/exception/invalidargumentexception "Symfony\Component\Console\Exception\InvalidArgumentException") | When an alias is invalid | ### array getAliases() Returns the aliases for the command. #### Return Value | | | | --- | --- | | array | An array of aliases for the command | ### string getSynopsis(bool $short = false) Returns the synopsis for the command. #### Parameters | | | | | --- | --- | --- | | bool | $short | Whether to show the short version of the synopsis (with options folded) or not | #### Return Value | | | | --- | --- | | string | The synopsis | ### $this addUsage(string $usage) Add a command usage example. #### Parameters | | | | | --- | --- | --- | | string | $usage | The usage, it'll be prefixed with the command name | #### Return Value | | | | --- | --- | | $this | | ### array getUsages() Returns alternative usages of the command. #### Return Value | | | | --- | --- | | array | | ### mixed getHelper(string $name) Gets a helper instance by name. #### Parameters | | | | | --- | --- | --- | | string | $name | The helper name | #### Return Value | | | | --- | --- | | mixed | The helper value | #### Exceptions | | | | --- | --- | | [LogicException](../../../component/console/exception/logicexception "Symfony\Component\Console\Exception\LogicException") | if no HelperSet is defined | | [InvalidArgumentException](../../../component/console/exception/invalidargumentexception "Symfony\Component\Console\Exception\InvalidArgumentException") | if the helper is not defined |
programming_docs
symfony LintCommand LintCommand ============ class **LintCommand** extends [Command](../../../component/console/command/command "Symfony\Component\Console\Command\Command") Command that will validate your template syntax and output encountered errors. Properties ---------- | | | | | | --- | --- | --- | --- | | static protected | $defaultName | | | Methods ------- | | | | | --- | --- | --- | | static string|null | [getDefaultName](#method_getDefaultName)() | from [Command](../../../component/console/command/command#method_getDefaultName "Symfony\Component\Console\Command\Command") | | | [\_\_construct](#method___construct)(Environment $twig) | | | | [ignoreValidationErrors](#method_ignoreValidationErrors)() Ignores validation errors. | from [Command](../../../component/console/command/command#method_ignoreValidationErrors "Symfony\Component\Console\Command\Command") | | | [setApplication](#method_setApplication)([Application](../../../component/console/application "Symfony\Component\Console\Application") $application = null) | from [Command](../../../component/console/command/command#method_setApplication "Symfony\Component\Console\Command\Command") | | | [setHelperSet](#method_setHelperSet)([HelperSet](../../../component/console/helper/helperset "Symfony\Component\Console\Helper\HelperSet") $helperSet) | from [Command](../../../component/console/command/command#method_setHelperSet "Symfony\Component\Console\Command\Command") | | [HelperSet](../../../component/console/helper/helperset "Symfony\Component\Console\Helper\HelperSet") | [getHelperSet](#method_getHelperSet)() Gets the helper set. | from [Command](../../../component/console/command/command#method_getHelperSet "Symfony\Component\Console\Command\Command") | | [Application](../../../component/console/application "Symfony\Component\Console\Application") | [getApplication](#method_getApplication)() Gets the application instance for this command. | from [Command](../../../component/console/command/command#method_getApplication "Symfony\Component\Console\Command\Command") | | bool | [isEnabled](#method_isEnabled)() Checks whether the command is enabled or not in the current environment. | from [Command](../../../component/console/command/command#method_isEnabled "Symfony\Component\Console\Command\Command") | | | [configure](#method_configure)() Configures the current command. | | | int|null | [execute](#method_execute)([InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") $input, [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") $output) Executes the current command. | | | | [interact](#method_interact)([InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") $input, [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") $output) Interacts with the user. | from [Command](../../../component/console/command/command#method_interact "Symfony\Component\Console\Command\Command") | | | [initialize](#method_initialize)([InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") $input, [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") $output) Initializes the command after the input has been bound and before the input is validated. | from [Command](../../../component/console/command/command#method_initialize "Symfony\Component\Console\Command\Command") | | int | [run](#method_run)([InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") $input, [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") $output) Runs the command. | from [Command](../../../component/console/command/command#method_run "Symfony\Component\Console\Command\Command") | | $this | [setCode](#method_setCode)(callable $code) Sets the code to execute when running this command. | from [Command](../../../component/console/command/command#method_setCode "Symfony\Component\Console\Command\Command") | | | [mergeApplicationDefinition](#method_mergeApplicationDefinition)(bool $mergeArgs = true) Merges the application definition with the command definition. | from [Command](../../../component/console/command/command#method_mergeApplicationDefinition "Symfony\Component\Console\Command\Command") | | $this | [setDefinition](#method_setDefinition)(array|[InputDefinition](../../../component/console/input/inputdefinition "Symfony\Component\Console\Input\InputDefinition") $definition) Sets an array of argument and option instances. | from [Command](../../../component/console/command/command#method_setDefinition "Symfony\Component\Console\Command\Command") | | [InputDefinition](../../../component/console/input/inputdefinition "Symfony\Component\Console\Input\InputDefinition") | [getDefinition](#method_getDefinition)() Gets the InputDefinition attached to this Command. | from [Command](../../../component/console/command/command#method_getDefinition "Symfony\Component\Console\Command\Command") | | [InputDefinition](../../../component/console/input/inputdefinition "Symfony\Component\Console\Input\InputDefinition") | [getNativeDefinition](#method_getNativeDefinition)() Gets the InputDefinition to be used to create representations of this Command. | from [Command](../../../component/console/command/command#method_getNativeDefinition "Symfony\Component\Console\Command\Command") | | $this | [addArgument](#method_addArgument)(string $name, int|null $mode = null, string $description = '', string|string[]|null $default = null) Adds an argument. | from [Command](../../../component/console/command/command#method_addArgument "Symfony\Component\Console\Command\Command") | | $this | [addOption](#method_addOption)(string $name, string|array $shortcut = null, int|null $mode = null, string $description = '', string|string[]|bool|null $default = null) Adds an option. | from [Command](../../../component/console/command/command#method_addOption "Symfony\Component\Console\Command\Command") | | $this | [setName](#method_setName)(string $name) Sets the name of the command. | from [Command](../../../component/console/command/command#method_setName "Symfony\Component\Console\Command\Command") | | $this | [setProcessTitle](#method_setProcessTitle)(string $title) Sets the process title of the command. | from [Command](../../../component/console/command/command#method_setProcessTitle "Symfony\Component\Console\Command\Command") | | string | [getName](#method_getName)() Returns the command name. | from [Command](../../../component/console/command/command#method_getName "Symfony\Component\Console\Command\Command") | | [Command](../../../component/console/command/command "Symfony\Component\Console\Command\Command") | [setHidden](#method_setHidden)(bool $hidden) | from [Command](../../../component/console/command/command#method_setHidden "Symfony\Component\Console\Command\Command") | | bool | [isHidden](#method_isHidden)() | from [Command](../../../component/console/command/command#method_isHidden "Symfony\Component\Console\Command\Command") | | $this | [setDescription](#method_setDescription)(string $description) Sets the description for the command. | from [Command](../../../component/console/command/command#method_setDescription "Symfony\Component\Console\Command\Command") | | string | [getDescription](#method_getDescription)() Returns the description for the command. | from [Command](../../../component/console/command/command#method_getDescription "Symfony\Component\Console\Command\Command") | | $this | [setHelp](#method_setHelp)(string $help) Sets the help for the command. | from [Command](../../../component/console/command/command#method_setHelp "Symfony\Component\Console\Command\Command") | | string | [getHelp](#method_getHelp)() Returns the help for the command. | from [Command](../../../component/console/command/command#method_getHelp "Symfony\Component\Console\Command\Command") | | string | [getProcessedHelp](#method_getProcessedHelp)() Returns the processed help for the command replacing the %command.name% and %command.full\_name% patterns with the real values dynamically. | from [Command](../../../component/console/command/command#method_getProcessedHelp "Symfony\Component\Console\Command\Command") | | $this | [setAliases](#method_setAliases)(string[] $aliases) Sets the aliases for the command. | from [Command](../../../component/console/command/command#method_setAliases "Symfony\Component\Console\Command\Command") | | array | [getAliases](#method_getAliases)() Returns the aliases for the command. | from [Command](../../../component/console/command/command#method_getAliases "Symfony\Component\Console\Command\Command") | | string | [getSynopsis](#method_getSynopsis)(bool $short = false) Returns the synopsis for the command. | from [Command](../../../component/console/command/command#method_getSynopsis "Symfony\Component\Console\Command\Command") | | $this | [addUsage](#method_addUsage)(string $usage) Add a command usage example. | from [Command](../../../component/console/command/command#method_addUsage "Symfony\Component\Console\Command\Command") | | array | [getUsages](#method_getUsages)() Returns alternative usages of the command. | from [Command](../../../component/console/command/command#method_getUsages "Symfony\Component\Console\Command\Command") | | mixed | [getHelper](#method_getHelper)(string $name) Gets a helper instance by name. | from [Command](../../../component/console/command/command#method_getHelper "Symfony\Component\Console\Command\Command") | | | [findFiles](#method_findFiles)($filename) | | Details ------- ### static string|null getDefaultName() #### Return Value | | | | --- | --- | | string|null | The default command name or null when no default name is set | ### \_\_construct(Environment $twig) #### Parameters | | | | | --- | --- | --- | | Environment | $twig | | #### Exceptions | | | | --- | --- | | [LogicException](../../../component/console/exception/logicexception "Symfony\Component\Console\Exception\LogicException") | When the command name is empty | ### ignoreValidationErrors() Ignores validation errors. This is mainly useful for the help command. ### setApplication([Application](../../../component/console/application "Symfony\Component\Console\Application") $application = null) #### Parameters | | | | | --- | --- | --- | | [Application](../../../component/console/application "Symfony\Component\Console\Application") | $application | | ### setHelperSet([HelperSet](../../../component/console/helper/helperset "Symfony\Component\Console\Helper\HelperSet") $helperSet) #### Parameters | | | | | --- | --- | --- | | [HelperSet](../../../component/console/helper/helperset "Symfony\Component\Console\Helper\HelperSet") | $helperSet | | ### [HelperSet](../../../component/console/helper/helperset "Symfony\Component\Console\Helper\HelperSet") getHelperSet() Gets the helper set. #### Return Value | | | | --- | --- | | [HelperSet](../../../component/console/helper/helperset "Symfony\Component\Console\Helper\HelperSet") | A HelperSet instance | ### [Application](../../../component/console/application "Symfony\Component\Console\Application") getApplication() Gets the application instance for this command. #### Return Value | | | | --- | --- | | [Application](../../../component/console/application "Symfony\Component\Console\Application") | An Application instance | ### bool isEnabled() Checks whether the command is enabled or not in the current environment. Override this to check for x or y and return false if the command can not run properly under the current conditions. #### Return Value | | | | --- | --- | | bool | | ### protected configure() Configures the current command. ### protected int|null execute([InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") $input, [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") $output) Executes the current command. This method is not abstract because you can use this class as a concrete class. In this case, instead of defining the execute() method, you set the code to execute by passing a Closure to the setCode() method. #### Parameters | | | | | --- | --- | --- | | [InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") | $input | | | [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") | $output | | #### Return Value | | | | --- | --- | | int|null | null or 0 if everything went fine, or an error code | #### Exceptions | | | | --- | --- | | [LogicException](../../../component/console/exception/logicexception "Symfony\Component\Console\Exception\LogicException") | When this abstract method is not implemented | ### protected interact([InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") $input, [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") $output) Interacts with the user. This method is executed before the InputDefinition is validated. This means that this is the only place where the command can interactively ask for values of missing required arguments. #### Parameters | | | | | --- | --- | --- | | [InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") | $input | | | [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") | $output | | ### protected initialize([InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") $input, [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") $output) Initializes the command after the input has been bound and before the input is validated. This is mainly useful when a lot of commands extends one main command where some things need to be initialized based on the input arguments and options. #### Parameters | | | | | --- | --- | --- | | [InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") | $input | | | [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") | $output | | #### See also | | | | --- | --- | | [InputInterface::bind](../../../component/console/input/inputinterface#method_bind "Symfony\Component\Console\Input\InputInterface") | | | [InputInterface::validate](../../../component/console/input/inputinterface#method_validate "Symfony\Component\Console\Input\InputInterface") | | ### int run([InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") $input, [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") $output) Runs the command. The code to execute is either defined directly with the setCode() method or by overriding the execute() method in a sub-class. #### Parameters | | | | | --- | --- | --- | | [InputInterface](../../../component/console/input/inputinterface "Symfony\Component\Console\Input\InputInterface") | $input | | | [OutputInterface](../../../component/console/output/outputinterface "Symfony\Component\Console\Output\OutputInterface") | $output | | #### Return Value | | | | --- | --- | | int | The command exit code | #### Exceptions | | | | --- | --- | | [Exception](http://php.net/Exception) | When binding input fails. Bypass this by calling {@link ignoreValidationErrors()}. | #### See also | | | | --- | --- | | setCode() | | | execute() | | ### $this setCode(callable $code) Sets the code to execute when running this command. If this method is used, it overrides the code defined in the execute() method. #### Parameters | | | | | --- | --- | --- | | callable | $code | A callable(InputInterface $input, OutputInterface $output) | #### Return Value | | | | --- | --- | | $this | | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](../../../component/console/exception/invalidargumentexception "Symfony\Component\Console\Exception\InvalidArgumentException") | | #### See also | | | | --- | --- | | execute() | | ### mergeApplicationDefinition(bool $mergeArgs = true) Merges the application definition with the command definition. This method is not part of public API and should not be used directly. #### Parameters | | | | | --- | --- | --- | | bool | $mergeArgs | Whether to merge or not the Application definition arguments to Command definition arguments | ### $this setDefinition(array|[InputDefinition](../../../component/console/input/inputdefinition "Symfony\Component\Console\Input\InputDefinition") $definition) Sets an array of argument and option instances. #### Parameters | | | | | --- | --- | --- | | array|[InputDefinition](../../../component/console/input/inputdefinition "Symfony\Component\Console\Input\InputDefinition") | $definition | An array of argument and option instances or a definition instance | #### Return Value | | | | --- | --- | | $this | | ### [InputDefinition](../../../component/console/input/inputdefinition "Symfony\Component\Console\Input\InputDefinition") getDefinition() Gets the InputDefinition attached to this Command. #### Return Value | | | | --- | --- | | [InputDefinition](../../../component/console/input/inputdefinition "Symfony\Component\Console\Input\InputDefinition") | An InputDefinition instance | ### [InputDefinition](../../../component/console/input/inputdefinition "Symfony\Component\Console\Input\InputDefinition") getNativeDefinition() Gets the InputDefinition to be used to create representations of this Command. Can be overridden to provide the original command representation when it would otherwise be changed by merging with the application InputDefinition. This method is not part of public API and should not be used directly. #### Return Value | | | | --- | --- | | [InputDefinition](../../../component/console/input/inputdefinition "Symfony\Component\Console\Input\InputDefinition") | An InputDefinition instance | ### $this addArgument(string $name, int|null $mode = null, string $description = '', string|string[]|null $default = null) Adds an argument. #### Parameters | | | | | --- | --- | --- | | string | $name | The argument name | | int|null | $mode | The argument mode: self::REQUIRED or self::OPTIONAL | | string | $description | A description text | | string|string[]|null | $default | The default value (for self::OPTIONAL mode only) | #### Return Value | | | | --- | --- | | $this | | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](../../../component/console/exception/invalidargumentexception "Symfony\Component\Console\Exception\InvalidArgumentException") | When argument mode is not valid | ### $this addOption(string $name, string|array $shortcut = null, int|null $mode = null, string $description = '', string|string[]|bool|null $default = null) Adds an option. #### Parameters | | | | | --- | --- | --- | | string | $name | The option name | | string|array | $shortcut | The shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts | | int|null | $mode | The option mode: One of the VALUE\_\* constants | | string | $description | A description text | | string|string[]|bool|null | $default | The default value (must be null for self::VALUE\_NONE) | #### Return Value | | | | --- | --- | | $this | | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](../../../component/console/exception/invalidargumentexception "Symfony\Component\Console\Exception\InvalidArgumentException") | If option mode is invalid or incompatible | ### $this setName(string $name) Sets the name of the command. This method can set both the namespace and the name if you separate them by a colon (:) ``` $command->setName('foo:bar'); ``` #### Parameters | | | | | --- | --- | --- | | string | $name | The command name | #### Return Value | | | | --- | --- | | $this | | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](../../../component/console/exception/invalidargumentexception "Symfony\Component\Console\Exception\InvalidArgumentException") | When the name is invalid | ### $this setProcessTitle(string $title) Sets the process title of the command. This feature should be used only when creating a long process command, like a daemon. PHP 5.5+ or the proctitle PECL library is required #### Parameters | | | | | --- | --- | --- | | string | $title | The process title | #### Return Value | | | | --- | --- | | $this | | ### string getName() Returns the command name. #### Return Value | | | | --- | --- | | string | The command name | ### [Command](../../../component/console/command/command "Symfony\Component\Console\Command\Command") setHidden(bool $hidden) #### Parameters | | | | | --- | --- | --- | | bool | $hidden | Whether or not the command should be hidden from the list of commands | #### Return Value | | | | --- | --- | | [Command](../../../component/console/command/command "Symfony\Component\Console\Command\Command") | The current instance | ### bool isHidden() #### Return Value | | | | --- | --- | | bool | whether the command should be publicly shown or not | ### $this setDescription(string $description) Sets the description for the command. #### Parameters | | | | | --- | --- | --- | | string | $description | The description for the command | #### Return Value | | | | --- | --- | | $this | | ### string getDescription() Returns the description for the command. #### Return Value | | | | --- | --- | | string | The description for the command | ### $this setHelp(string $help) Sets the help for the command. #### Parameters | | | | | --- | --- | --- | | string | $help | The help for the command | #### Return Value | | | | --- | --- | | $this | | ### string getHelp() Returns the help for the command. #### Return Value | | | | --- | --- | | string | The help for the command | ### string getProcessedHelp() Returns the processed help for the command replacing the %command.name% and %command.full\_name% patterns with the real values dynamically. #### Return Value | | | | --- | --- | | string | The processed help for the command | ### $this setAliases(string[] $aliases) Sets the aliases for the command. #### Parameters | | | | | --- | --- | --- | | string[] | $aliases | An array of aliases for the command | #### Return Value | | | | --- | --- | | $this | | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](../../../component/console/exception/invalidargumentexception "Symfony\Component\Console\Exception\InvalidArgumentException") | When an alias is invalid | ### array getAliases() Returns the aliases for the command. #### Return Value | | | | --- | --- | | array | An array of aliases for the command | ### string getSynopsis(bool $short = false) Returns the synopsis for the command. #### Parameters | | | | | --- | --- | --- | | bool | $short | Whether to show the short version of the synopsis (with options folded) or not | #### Return Value | | | | --- | --- | | string | The synopsis | ### $this addUsage(string $usage) Add a command usage example. #### Parameters | | | | | --- | --- | --- | | string | $usage | The usage, it'll be prefixed with the command name | #### Return Value | | | | --- | --- | | $this | | ### array getUsages() Returns alternative usages of the command. #### Return Value | | | | --- | --- | | array | | ### mixed getHelper(string $name) Gets a helper instance by name. #### Parameters | | | | | --- | --- | --- | | string | $name | The helper name | #### Return Value | | | | --- | --- | | mixed | The helper value | #### Exceptions | | | | --- | --- | | [LogicException](../../../component/console/exception/logicexception "Symfony\Component\Console\Exception\LogicException") | if no HelperSet is defined | | [InvalidArgumentException](../../../component/console/exception/invalidargumentexception "Symfony\Component\Console\Exception\InvalidArgumentException") | if the helper is not defined | ### protected findFiles($filename) #### Parameters | | | | | --- | --- | --- | | | $filename | |
programming_docs
symfony FormThemeTokenParser FormThemeTokenParser ===================== class **FormThemeTokenParser** extends AbstractTokenParser Token Parser for the 'form\_theme' tag. Methods ------- | | | | | --- | --- | --- | | Node | [parse](#method_parse)(Token $token) Parses a token and returns a node. | | | string | [getTag](#method_getTag)() Gets the tag name associated with this token parser. | | Details ------- ### Node parse(Token $token) Parses a token and returns a node. #### Parameters | | | | | --- | --- | --- | | Token | $token | | #### Return Value | | | | --- | --- | | Node | | ### string getTag() Gets the tag name associated with this token parser. #### Return Value | | | | --- | --- | | string | The tag name | symfony TransChoiceTokenParser TransChoiceTokenParser ======================= class **TransChoiceTokenParser** extends [TransTokenParser](transtokenparser "Symfony\Bridge\Twig\TokenParser\TransTokenParser") Token Parser for the 'transchoice' tag. Methods ------- | | | | | --- | --- | --- | | Node | [parse](#method_parse)(Token $token) Parses a token and returns a node. | | | | [decideTransFork](#method_decideTransFork)($token) | from [TransTokenParser](transtokenparser#method_decideTransFork "Symfony\Bridge\Twig\TokenParser\TransTokenParser") | | string | [getTag](#method_getTag)() Gets the tag name associated with this token parser. | | | | [decideTransChoiceFork](#method_decideTransChoiceFork)($token) | | Details ------- ### Node parse(Token $token) Parses a token and returns a node. #### Parameters | | | | | --- | --- | --- | | Token | $token | | #### Return Value | | | | --- | --- | | Node | | #### Exceptions | | | | --- | --- | | SyntaxError | | ### decideTransFork($token) #### Parameters | | | | | --- | --- | --- | | | $token | | ### string getTag() Gets the tag name associated with this token parser. #### Return Value | | | | --- | --- | | string | The tag name | ### decideTransChoiceFork($token) #### Parameters | | | | | --- | --- | --- | | | $token | | symfony DumpTokenParser DumpTokenParser ================ class **DumpTokenParser** extends AbstractTokenParser Token Parser for the 'dump' tag. Dump variables with: ``` {% dump %} {% dump foo %} {% dump foo, bar %} ``` Methods ------- | | | | | --- | --- | --- | | | [parse](#method_parse)(Token $token) {@inheritdoc} | | | | [getTag](#method_getTag)() {@inheritdoc} | | Details ------- ### parse(Token $token) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | Token | $token | | ### getTag() {@inheritdoc} symfony TransTokenParser TransTokenParser ================= class **TransTokenParser** extends AbstractTokenParser Token Parser for the 'trans' tag. Methods ------- | | | | | --- | --- | --- | | Node | [parse](#method_parse)(Token $token) Parses a token and returns a node. | | | | [decideTransFork](#method_decideTransFork)($token) | | | string | [getTag](#method_getTag)() Gets the tag name associated with this token parser. | | Details ------- ### Node parse(Token $token) Parses a token and returns a node. #### Parameters | | | | | --- | --- | --- | | Token | $token | | #### Return Value | | | | --- | --- | | Node | | #### Exceptions | | | | --- | --- | | SyntaxError | | ### decideTransFork($token) #### Parameters | | | | | --- | --- | --- | | | $token | | ### string getTag() Gets the tag name associated with this token parser. #### Return Value | | | | --- | --- | | string | The tag name | symfony TransDefaultDomainTokenParser TransDefaultDomainTokenParser ============================== class **TransDefaultDomainTokenParser** extends AbstractTokenParser Token Parser for the 'trans\_default\_domain' tag. Methods ------- | | | | | --- | --- | --- | | Node | [parse](#method_parse)(Token $token) Parses a token and returns a node. | | | string | [getTag](#method_getTag)() Gets the tag name associated with this token parser. | | Details ------- ### Node parse(Token $token) Parses a token and returns a node. #### Parameters | | | | | --- | --- | --- | | Token | $token | | #### Return Value | | | | --- | --- | | Node | | ### string getTag() Gets the tag name associated with this token parser. #### Return Value | | | | --- | --- | | string | The tag name | symfony StopwatchTokenParser StopwatchTokenParser ===================== class **StopwatchTokenParser** extends AbstractTokenParser Token Parser for the stopwatch tag. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $stopwatchIsAvailable | | | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(bool $stopwatchIsAvailable) | | | | [parse](#method_parse)(Token $token) | | | | [decideStopwatchEnd](#method_decideStopwatchEnd)(Token $token) | | | | [getTag](#method_getTag)() | | Details ------- ### \_\_construct(bool $stopwatchIsAvailable) #### Parameters | | | | | --- | --- | --- | | bool | $stopwatchIsAvailable | | ### parse(Token $token) #### Parameters | | | | | --- | --- | --- | | Token | $token | | ### decideStopwatchEnd(Token $token) #### Parameters | | | | | --- | --- | --- | | Token | $token | | ### getTag() symfony TransNode TransNode ========== class **TransNode** extends Node Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(Node $body, Node $domain = null, AbstractExpression $count = null, AbstractExpression $vars = null, AbstractExpression $locale = null, int $lineno = 0, string $tag = null) | | | | [compile](#method_compile)(Compiler $compiler) | | | | [compileString](#method_compileString)(Node $body, ArrayExpression $vars, $ignoreStrictCheck = false) | | Details ------- ### \_\_construct(Node $body, Node $domain = null, AbstractExpression $count = null, AbstractExpression $vars = null, AbstractExpression $locale = null, int $lineno = 0, string $tag = null) #### Parameters | | | | | --- | --- | --- | | Node | $body | | | Node | $domain | | | AbstractExpression | $count | | | AbstractExpression | $vars | | | AbstractExpression | $locale | | | int | $lineno | | | string | $tag | | ### compile(Compiler $compiler) #### Parameters | | | | | --- | --- | --- | | Compiler | $compiler | | ### protected compileString(Node $body, ArrayExpression $vars, $ignoreStrictCheck = false) #### Parameters | | | | | --- | --- | --- | | Node | $body | | | ArrayExpression | $vars | | | | $ignoreStrictCheck | | symfony RenderBlockNode RenderBlockNode ================ class **RenderBlockNode** extends FunctionExpression Compiles a call to {@link \Symfony\Component\Form\FormRendererInterface::renderBlock()}. The function name is used as block name. For example, if the function name is "foo", the block "foo" will be rendered. Methods ------- | | | | | --- | --- | --- | | | [compile](#method_compile)(Compiler $compiler) | | Details ------- ### compile(Compiler $compiler) #### Parameters | | | | | --- | --- | --- | | Compiler | $compiler | | symfony FormThemeNode FormThemeNode ============== class **FormThemeNode** extends Node Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(Node $form, Node $resources, int $lineno, string $tag = null, bool $only = false) | | | | [compile](#method_compile)(Compiler $compiler) | | Details ------- ### \_\_construct(Node $form, Node $resources, int $lineno, string $tag = null, bool $only = false) #### Parameters | | | | | --- | --- | --- | | Node | $form | | | Node | $resources | | | int | $lineno | | | string | $tag | | | bool | $only | | ### compile(Compiler $compiler) #### Parameters | | | | | --- | --- | --- | | Compiler | $compiler | | symfony DumpNode DumpNode ========= class **DumpNode** extends Node Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)($varPrefix, Node $values = null, int $lineno, string $tag = null) | | | | [compile](#method_compile)(Compiler $compiler) {@inheritdoc} | | Details ------- ### \_\_construct($varPrefix, Node $values = null, int $lineno, string $tag = null) #### Parameters | | | | | --- | --- | --- | | | $varPrefix | | | Node | $values | | | int | $lineno | | | string | $tag | | ### compile(Compiler $compiler) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | Compiler | $compiler | | symfony StopwatchNode StopwatchNode ============== class **StopwatchNode** extends Node Represents a stopwatch node. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(Node $name, Node $body, AssignNameExpression $var, int $lineno = 0, string $tag = null) | | | | [compile](#method_compile)(Compiler $compiler) | | Details ------- ### \_\_construct(Node $name, Node $body, AssignNameExpression $var, int $lineno = 0, string $tag = null) #### Parameters | | | | | --- | --- | --- | | Node | $name | | | Node | $body | | | AssignNameExpression | $var | | | int | $lineno | | | string | $tag | | ### compile(Compiler $compiler) #### Parameters | | | | | --- | --- | --- | | Compiler | $compiler | | symfony SearchAndRenderBlockNode SearchAndRenderBlockNode ========================= class **SearchAndRenderBlockNode** extends FunctionExpression Methods ------- | | | | | --- | --- | --- | | | [compile](#method_compile)(Compiler $compiler) | | Details ------- ### compile(Compiler $compiler) #### Parameters | | | | | --- | --- | --- | | Compiler | $compiler | | symfony TransDefaultDomainNode TransDefaultDomainNode ======================= class **TransDefaultDomainNode** extends Node Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(AbstractExpression $expr, int $lineno = 0, string $tag = null) | | | | [compile](#method_compile)(Compiler $compiler) | | Details ------- ### \_\_construct(AbstractExpression $expr, int $lineno = 0, string $tag = null) #### Parameters | | | | | --- | --- | --- | | AbstractExpression | $expr | | | int | $lineno | | | string | $tag | | ### compile(Compiler $compiler) #### Parameters | | | | | --- | --- | --- | | Compiler | $compiler | | symfony Symfony\Bridge\ProxyManager\LazyProxy Symfony\Bridge\ProxyManager\LazyProxy ===================================== Namespaces ---------- [Symfony\Bridge\ProxyManager\LazyProxy\Instantiator](lazyproxy/instantiator)[Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper](lazyproxy/phpdumper) symfony Symfony\Bridge\ProxyManager\LazyProxy\Instantiator Symfony\Bridge\ProxyManager\LazyProxy\Instantiator ================================================== Classes ------- | | | | --- | --- | | [LazyLoadingValueHolderFactoryV1](instantiator/lazyloadingvalueholderfactoryv1 "Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\LazyLoadingValueHolderFactoryV1") | | | [LazyLoadingValueHolderFactoryV2](instantiator/lazyloadingvalueholderfactoryv2 "Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\LazyLoadingValueHolderFactoryV2") | | | [RuntimeInstantiator](instantiator/runtimeinstantiator "Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\RuntimeInstantiator") | Runtime lazy loading proxy generator. | symfony Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper =============================================== Classes ------- | | | | --- | --- | | [LazyLoadingValueHolderGenerator](phpdumper/lazyloadingvalueholdergenerator "Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\LazyLoadingValueHolderGenerator") | | | [ProxyDumper](phpdumper/proxydumper "Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper") | Generates dumped PHP code of proxies via reflection. | symfony ProxyDumper ProxyDumper ============ class **ProxyDumper** implements [DumperInterface](../../../../component/dependencyinjection/lazyproxy/phpdumper/dumperinterface "Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface") Generates dumped PHP code of proxies via reflection. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $salt = '') | | | bool | [isProxyCandidate](#method_isProxyCandidate)([Definition](../../../../component/dependencyinjection/definition "Symfony\Component\DependencyInjection\Definition") $definition) Inspects whether the given definitions should produce proxy instantiation logic in the dumped container. | | | string | [getProxyFactoryCode](#method_getProxyFactoryCode)([Definition](../../../../component/dependencyinjection/definition "Symfony\Component\DependencyInjection\Definition") $definition, string $id, string $factoryCode = null) Generates the code to be used to instantiate a proxy in the dumped factory code. | | | string | [getProxyCode](#method_getProxyCode)([Definition](../../../../component/dependencyinjection/definition "Symfony\Component\DependencyInjection\Definition") $definition) Generates the code for the lazy proxy. | | Details ------- ### \_\_construct(string $salt = '') #### Parameters | | | | | --- | --- | --- | | string | $salt | | ### bool isProxyCandidate([Definition](../../../../component/dependencyinjection/definition "Symfony\Component\DependencyInjection\Definition") $definition) Inspects whether the given definitions should produce proxy instantiation logic in the dumped container. #### Parameters | | | | | --- | --- | --- | | [Definition](../../../../component/dependencyinjection/definition "Symfony\Component\DependencyInjection\Definition") | $definition | | #### Return Value | | | | --- | --- | | bool | | ### string getProxyFactoryCode([Definition](../../../../component/dependencyinjection/definition "Symfony\Component\DependencyInjection\Definition") $definition, string $id, string $factoryCode = null) Generates the code to be used to instantiate a proxy in the dumped factory code. #### Parameters | | | | | --- | --- | --- | | [Definition](../../../../component/dependencyinjection/definition "Symfony\Component\DependencyInjection\Definition") | $definition | | | string | $id | Service identifier | | string | $factoryCode | The code to execute to create the service | #### Return Value | | | | --- | --- | | string | | ### string getProxyCode([Definition](../../../../component/dependencyinjection/definition "Symfony\Component\DependencyInjection\Definition") $definition) Generates the code for the lazy proxy. #### Parameters | | | | | --- | --- | --- | | [Definition](../../../../component/dependencyinjection/definition "Symfony\Component\DependencyInjection\Definition") | $definition | | #### Return Value | | | | --- | --- | | string | | symfony LazyLoadingValueHolderGenerator LazyLoadingValueHolderGenerator ================================ class **LazyLoadingValueHolderGenerator** extends LazyLoadingValueHolderGenerator Methods ------- | | | | | --- | --- | --- | | | [generate](#method_generate)([ReflectionClass](http://php.net/ReflectionClass) $originalClass, ClassGenerator $classGenerator) {@inheritdoc} | | Details ------- ### generate([ReflectionClass](http://php.net/ReflectionClass) $originalClass, ClassGenerator $classGenerator) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | [ReflectionClass](http://php.net/ReflectionClass) | $originalClass | | | ClassGenerator | $classGenerator | | symfony LazyLoadingValueHolderFactoryV2 LazyLoadingValueHolderFactoryV2 ================================ class **LazyLoadingValueHolderFactoryV2** extends LazyLoadingValueHolderFactory Methods ------- | | | | | --- | --- | --- | | ProxyGeneratorInterface | [getGenerator](#method_getGenerator)() {@inheritdoc} | | Details ------- ### protected ProxyGeneratorInterface getGenerator() {@inheritdoc} #### Return Value | | | | --- | --- | | ProxyGeneratorInterface | | symfony RuntimeInstantiator RuntimeInstantiator ==================== class **RuntimeInstantiator** implements [InstantiatorInterface](../../../../component/dependencyinjection/lazyproxy/instantiator/instantiatorinterface "Symfony\Component\DependencyInjection\LazyProxy\Instantiator\InstantiatorInterface") Runtime lazy loading proxy generator. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)() | | | object | [instantiateProxy](#method_instantiateProxy)([ContainerInterface](../../../../component/dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface") $container, [Definition](../../../../component/dependencyinjection/definition "Symfony\Component\DependencyInjection\Definition") $definition, string $id, callable $realInstantiator) Instantiates a proxy object. | | Details ------- ### \_\_construct() ### object instantiateProxy([ContainerInterface](../../../../component/dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface") $container, [Definition](../../../../component/dependencyinjection/definition "Symfony\Component\DependencyInjection\Definition") $definition, string $id, callable $realInstantiator) Instantiates a proxy object. #### Parameters | | | | | --- | --- | --- | | [ContainerInterface](../../../../component/dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface") | $container | The container from which the service is being requested | | [Definition](../../../../component/dependencyinjection/definition "Symfony\Component\DependencyInjection\Definition") | $definition | The definition of the requested service | | string | $id | Identifier of the requested service | | callable | $realInstantiator | Zero-argument callback that is capable of producing the real service instance | #### Return Value | | | | --- | --- | | object | | symfony LazyLoadingValueHolderFactoryV1 LazyLoadingValueHolderFactoryV1 ================================ class **LazyLoadingValueHolderFactoryV1** extends LazyLoadingValueHolderFactory Methods ------- | | | | | --- | --- | --- | | | [getGenerator](#method_getGenerator)() {@inheritdoc} | | Details ------- ### protected getGenerator() {@inheritdoc} symfony Symfony\Component\WebLink Symfony\Component\WebLink ========================= Namespaces ---------- [Symfony\Component\WebLink\EventListener](weblink/eventlistener) Classes ------- | | | | --- | --- | | [HttpHeaderSerializer](weblink/httpheaderserializer "Symfony\Component\WebLink\HttpHeaderSerializer") | Serializes a list of Link instances to a HTTP Link header. | symfony Symfony\Component\HttpKernel Symfony\Component\HttpKernel ============================ Namespaces ---------- [Symfony\Component\HttpKernel\Bundle](httpkernel/bundle)[Symfony\Component\HttpKernel\CacheClearer](httpkernel/cacheclearer)[Symfony\Component\HttpKernel\CacheWarmer](httpkernel/cachewarmer)[Symfony\Component\HttpKernel\Config](httpkernel/config)[Symfony\Component\HttpKernel\Controller](httpkernel/controller)[Symfony\Component\HttpKernel\ControllerMetadata](httpkernel/controllermetadata)[Symfony\Component\HttpKernel\DataCollector](httpkernel/datacollector)[Symfony\Component\HttpKernel\Debug](httpkernel/debug)[Symfony\Component\HttpKernel\DependencyInjection](httpkernel/dependencyinjection)[Symfony\Component\HttpKernel\Event](httpkernel/event)[Symfony\Component\HttpKernel\EventListener](httpkernel/eventlistener)[Symfony\Component\HttpKernel\Exception](httpkernel/exception)[Symfony\Component\HttpKernel\Fragment](httpkernel/fragment)[Symfony\Component\HttpKernel\HttpCache](httpkernel/httpcache)[Symfony\Component\HttpKernel\Log](httpkernel/log)[Symfony\Component\HttpKernel\Profiler](httpkernel/profiler) Classes ------- | | | | --- | --- | | [Client](httpkernel/client "Symfony\Component\HttpKernel\Client") | Client simulates a browser and makes requests to a Kernel object. | | [HttpKernel](httpkernel/httpkernel "Symfony\Component\HttpKernel\HttpKernel") | HttpKernel notifies events to convert a Request object to a Response one. | | [Kernel](httpkernel/kernel "Symfony\Component\HttpKernel\Kernel") | The Kernel is the heart of the Symfony system. | | [KernelEvents](httpkernel/kernelevents "Symfony\Component\HttpKernel\KernelEvents") | Contains all events thrown in the HttpKernel component. | | [UriSigner](httpkernel/urisigner "Symfony\Component\HttpKernel\UriSigner") | Signs URIs. | Interfaces ---------- | | | | --- | --- | | *[HttpKernelInterface](httpkernel/httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface")* | HttpKernelInterface handles a Request to convert it to a Response. | | *[KernelInterface](httpkernel/kernelinterface "Symfony\Component\HttpKernel\KernelInterface")* | The Kernel is the heart of the Symfony system. | | *[RebootableInterface](httpkernel/rebootableinterface "Symfony\Component\HttpKernel\RebootableInterface")* | Allows the Kernel to be rebooted using a temporary cache directory. | | *[TerminableInterface](httpkernel/terminableinterface "Symfony\Component\HttpKernel\TerminableInterface")* | Terminable extends the Kernel request/response cycle with dispatching a post response event after sending the response and before shutting down the kernel. |
programming_docs
symfony Symfony\Component\Filesystem Symfony\Component\Filesystem ============================ Namespaces ---------- [Symfony\Component\Filesystem\Exception](filesystem/exception) Classes ------- | | | | --- | --- | | [Filesystem](filesystem/filesystem "Symfony\Component\Filesystem\Filesystem") | Provides basic utility to manipulate the file system. | symfony Symfony\Component\DomCrawler Symfony\Component\DomCrawler ============================ Namespaces ---------- [Symfony\Component\DomCrawler\Field](domcrawler/field) Classes ------- | | | | --- | --- | | [AbstractUriElement](domcrawler/abstracturielement "Symfony\Component\DomCrawler\AbstractUriElement") | Any HTML element that can link to an URI. | | [Crawler](domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") | Crawler eases navigation of a list of \DOMNode objects. | | [Form](domcrawler/form "Symfony\Component\DomCrawler\Form") | Form represents an HTML form. | | [FormFieldRegistry](domcrawler/formfieldregistry "Symfony\Component\DomCrawler\FormFieldRegistry") | This is an internal class that must not be used directly. | | [Image](domcrawler/image "Symfony\Component\DomCrawler\Image") | Image represents an HTML image (an HTML img tag). | | [Link](domcrawler/link "Symfony\Component\DomCrawler\Link") | Link represents an HTML link (an HTML a, area or link tag). | symfony Symfony\Component\Asset Symfony\Component\Asset ======================= Namespaces ---------- [Symfony\Component\Asset\Context](asset/context)[Symfony\Component\Asset\Exception](asset/exception)[Symfony\Component\Asset\VersionStrategy](asset/versionstrategy) Classes ------- | | | | --- | --- | | [Package](asset/package "Symfony\Component\Asset\Package") | Basic package that adds a version to asset URLs. | | [Packages](asset/packages "Symfony\Component\Asset\Packages") | Helps manage asset URLs. | | [PathPackage](asset/pathpackage "Symfony\Component\Asset\PathPackage") | Package that adds a base path to asset URLs in addition to a version. | | [UrlPackage](asset/urlpackage "Symfony\Component\Asset\UrlPackage") | Package that adds a base URL to asset URLs in addition to a version. | Interfaces ---------- | | | | --- | --- | | *[PackageInterface](asset/packageinterface "Symfony\Component\Asset\PackageInterface")* | Asset package interface. | symfony Symfony\Component\Form Symfony\Component\Form ====================== Namespaces ---------- [Symfony\Component\Form\ChoiceList](form/choicelist)[Symfony\Component\Form\Command](form/command)[Symfony\Component\Form\Console](form/console)[Symfony\Component\Form\DependencyInjection](form/dependencyinjection)[Symfony\Component\Form\Exception](form/exception)[Symfony\Component\Form\Extension](form/extension)[Symfony\Component\Form\Guess](form/guess)[Symfony\Component\Form\Test](form/test)[Symfony\Component\Form\Util](form/util) Classes ------- | | | | --- | --- | | [AbstractExtension](form/abstractextension "Symfony\Component\Form\AbstractExtension") | | | [AbstractRendererEngine](form/abstractrendererengine "Symfony\Component\Form\AbstractRendererEngine") | Default implementation of {@link FormRendererEngineInterface}. | | [AbstractType](form/abstracttype "Symfony\Component\Form\AbstractType") | | | [AbstractTypeExtension](form/abstracttypeextension "Symfony\Component\Form\AbstractTypeExtension") | | | [Button](form/button "Symfony\Component\Form\Button") | A form button. | | [ButtonBuilder](form/buttonbuilder "Symfony\Component\Form\ButtonBuilder") | A builder for {@link Button} instances. | | [CallbackTransformer](form/callbacktransformer "Symfony\Component\Form\CallbackTransformer") | | | [Form](form/form "Symfony\Component\Form\Form") | Form represents a form. | | [FormBuilder](form/formbuilder "Symfony\Component\Form\FormBuilder") | A builder for creating {@link Form} instances. | | [FormConfigBuilder](form/formconfigbuilder "Symfony\Component\Form\FormConfigBuilder") | A basic form configuration. | | [FormError](form/formerror "Symfony\Component\Form\FormError") | Wraps errors in forms. | | [FormErrorIterator](form/formerroriterator "Symfony\Component\Form\FormErrorIterator") | Iterates over the errors of a form. | | [FormEvent](form/formevent "Symfony\Component\Form\FormEvent") | | | [FormEvents](form/formevents "Symfony\Component\Form\FormEvents") | To learn more about how form events work check the documentation entry at {@link https://symfony.com/doc/any/components/form/form\_events.html}. | | [FormFactory](form/formfactory "Symfony\Component\Form\FormFactory") | | | [FormFactoryBuilder](form/formfactorybuilder "Symfony\Component\Form\FormFactoryBuilder") | The default implementation of FormFactoryBuilderInterface. | | [FormRegistry](form/formregistry "Symfony\Component\Form\FormRegistry") | The central registry of the Form component. | | [FormRenderer](form/formrenderer "Symfony\Component\Form\FormRenderer") | Renders a form into HTML using a rendering engine. | | [FormTypeGuesserChain](form/formtypeguesserchain "Symfony\Component\Form\FormTypeGuesserChain") | | | [FormView](form/formview "Symfony\Component\Form\FormView") | | | [Forms](form/forms "Symfony\Component\Form\Forms") | Entry point of the Form component. | | [NativeRequestHandler](form/nativerequesthandler "Symfony\Component\Form\NativeRequestHandler") | A request handler using PHP's super globals $\_GET, $\_POST and $\_SERVER. | | [PreloadedExtension](form/preloadedextension "Symfony\Component\Form\PreloadedExtension") | A form extension with preloaded types, type extensions and type guessers. | | [ResolvedFormType](form/resolvedformtype "Symfony\Component\Form\ResolvedFormType") | A wrapper for a form type and its extensions. | | [ResolvedFormTypeFactory](form/resolvedformtypefactory "Symfony\Component\Form\ResolvedFormTypeFactory") | | | [ReversedTransformer](form/reversedtransformer "Symfony\Component\Form\ReversedTransformer") | Reverses a transformer. | | [SubmitButton](form/submitbutton "Symfony\Component\Form\SubmitButton") | A button that submits the form. | | [SubmitButtonBuilder](form/submitbuttonbuilder "Symfony\Component\Form\SubmitButtonBuilder") | A builder for {@link SubmitButton} instances. | Interfaces ---------- | | | | --- | --- | | *[ButtonTypeInterface](form/buttontypeinterface "Symfony\Component\Form\ButtonTypeInterface")* | A type that should be converted into a {@link Button} instance. | | *[ClickableInterface](form/clickableinterface "Symfony\Component\Form\ClickableInterface")* | A clickable form element. | | *[DataMapperInterface](form/datamapperinterface "Symfony\Component\Form\DataMapperInterface")* | | | *[DataTransformerInterface](form/datatransformerinterface "Symfony\Component\Form\DataTransformerInterface")* | Transforms a value between different representations. | | *[FormBuilderInterface](form/formbuilderinterface "Symfony\Component\Form\FormBuilderInterface")* | | | *[FormConfigBuilderInterface](form/formconfigbuilderinterface "Symfony\Component\Form\FormConfigBuilderInterface")* | | | *[FormConfigInterface](form/formconfiginterface "Symfony\Component\Form\FormConfigInterface")* | The configuration of a {@link Form} object. | | *[FormExtensionInterface](form/formextensioninterface "Symfony\Component\Form\FormExtensionInterface")* | Interface for extensions which provide types, type extensions and a guesser. | | *[FormFactoryBuilderInterface](form/formfactorybuilderinterface "Symfony\Component\Form\FormFactoryBuilderInterface")* | A builder for FormFactoryInterface objects. | | *[FormFactoryInterface](form/formfactoryinterface "Symfony\Component\Form\FormFactoryInterface")* | | | *[FormInterface](form/forminterface "Symfony\Component\Form\FormInterface")* | A form group bundling multiple forms in a hierarchical structure. | | *[FormRegistryInterface](form/formregistryinterface "Symfony\Component\Form\FormRegistryInterface")* | The central registry of the Form component. | | *[FormRendererEngineInterface](form/formrendererengineinterface "Symfony\Component\Form\FormRendererEngineInterface")* | Adapter for rendering form templates with a specific templating engine. | | *[FormRendererInterface](form/formrendererinterface "Symfony\Component\Form\FormRendererInterface")* | Renders a form into HTML. | | *[FormTypeExtensionInterface](form/formtypeextensioninterface "Symfony\Component\Form\FormTypeExtensionInterface")* | | | *[FormTypeGuesserInterface](form/formtypeguesserinterface "Symfony\Component\Form\FormTypeGuesserInterface")* | | | *[FormTypeInterface](form/formtypeinterface "Symfony\Component\Form\FormTypeInterface")* | | | *[RequestHandlerInterface](form/requesthandlerinterface "Symfony\Component\Form\RequestHandlerInterface")* | Submits forms if they were submitted. | | *[ResolvedFormTypeFactoryInterface](form/resolvedformtypefactoryinterface "Symfony\Component\Form\ResolvedFormTypeFactoryInterface")* | Creates ResolvedFormTypeInterface instances. | | *[ResolvedFormTypeInterface](form/resolvedformtypeinterface "Symfony\Component\Form\ResolvedFormTypeInterface")* | A wrapper for a form type and its extensions. | | *[SubmitButtonTypeInterface](form/submitbuttontypeinterface "Symfony\Component\Form\SubmitButtonTypeInterface")* | A type that should be converted into a {@link SubmitButton} instance. | symfony Symfony\Component\Routing Symfony\Component\Routing ========================= Namespaces ---------- [Symfony\Component\Routing\Annotation](routing/annotation)[Symfony\Component\Routing\DependencyInjection](routing/dependencyinjection)[Symfony\Component\Routing\Exception](routing/exception)[Symfony\Component\Routing\Generator](routing/generator)[Symfony\Component\Routing\Loader](routing/loader)[Symfony\Component\Routing\Matcher](routing/matcher) Classes ------- | | | | --- | --- | | [CompiledRoute](routing/compiledroute "Symfony\Component\Routing\CompiledRoute") | CompiledRoutes are returned by the RouteCompiler class. | | [RequestContext](routing/requestcontext "Symfony\Component\Routing\RequestContext") | Holds information about the current request. | | [Route](routing/route "Symfony\Component\Routing\Route") | A Route describes a route and its parameters. | | [RouteCollection](routing/routecollection "Symfony\Component\Routing\RouteCollection") | A RouteCollection represents a set of Route instances. | | [RouteCollectionBuilder](routing/routecollectionbuilder "Symfony\Component\Routing\RouteCollectionBuilder") | Helps add and import routes into a RouteCollection. | | [RouteCompiler](routing/routecompiler "Symfony\Component\Routing\RouteCompiler") | RouteCompiler compiles Route instances to CompiledRoute instances. | | [Router](routing/router "Symfony\Component\Routing\Router") | The Router class is an example of the integration of all pieces of the routing system for easier use. | Interfaces ---------- | | | | --- | --- | | *[RequestContextAwareInterface](routing/requestcontextawareinterface "Symfony\Component\Routing\RequestContextAwareInterface")* | | | *[RouteCompilerInterface](routing/routecompilerinterface "Symfony\Component\Routing\RouteCompilerInterface")* | RouteCompilerInterface is the interface that all RouteCompiler classes must implement. | | *[RouterInterface](routing/routerinterface "Symfony\Component\Routing\RouterInterface")* | RouterInterface is the interface that all Router classes must implement. | symfony Symfony\Component\Intl Symfony\Component\Intl ====================== Namespaces ---------- [Symfony\Component\Intl\Collator](intl/collator)[Symfony\Component\Intl\Data](intl/data)[Symfony\Component\Intl\DateFormatter](intl/dateformatter)[Symfony\Component\Intl\Exception](intl/exception)[Symfony\Component\Intl\Globals](intl/globals)[Symfony\Component\Intl\Locale](intl/locale)[Symfony\Component\Intl\NumberFormatter](intl/numberformatter)[Symfony\Component\Intl\ResourceBundle](intl/resourcebundle)[Symfony\Component\Intl\Util](intl/util) Classes ------- | | | | --- | --- | | [Intl](intl/intl "Symfony\Component\Intl\Intl") | Gives access to internationalization data. | | [Locale](intl/locale "Symfony\Component\Intl\Locale") | Provides access to locale-related data. | symfony Symfony\Component\ExpressionLanguage Symfony\Component\ExpressionLanguage ==================================== Namespaces ---------- [Symfony\Component\ExpressionLanguage\Node](expressionlanguage/node) Classes ------- | | | | --- | --- | | [Compiler](expressionlanguage/compiler "Symfony\Component\ExpressionLanguage\Compiler") | Compiles a node to PHP code. | | [Expression](expressionlanguage/expression "Symfony\Component\ExpressionLanguage\Expression") | Represents an expression. | | [ExpressionFunction](expressionlanguage/expressionfunction "Symfony\Component\ExpressionLanguage\ExpressionFunction") | Represents a function that can be used in an expression. | | [ExpressionLanguage](expressionlanguage/expressionlanguage "Symfony\Component\ExpressionLanguage\ExpressionLanguage") | Allows to compile and evaluate expressions written in your own DSL. | | [Lexer](expressionlanguage/lexer "Symfony\Component\ExpressionLanguage\Lexer") | Lexes an expression. | | [ParsedExpression](expressionlanguage/parsedexpression "Symfony\Component\ExpressionLanguage\ParsedExpression") | Represents an already parsed expression. | | [Parser](expressionlanguage/parser "Symfony\Component\ExpressionLanguage\Parser") | Parsers a token stream. | | [SerializedParsedExpression](expressionlanguage/serializedparsedexpression "Symfony\Component\ExpressionLanguage\SerializedParsedExpression") | Represents an already parsed expression. | | [SyntaxError](expressionlanguage/syntaxerror "Symfony\Component\ExpressionLanguage\SyntaxError") | | | [Token](expressionlanguage/token "Symfony\Component\ExpressionLanguage\Token") | Represents a Token. | | [TokenStream](expressionlanguage/tokenstream "Symfony\Component\ExpressionLanguage\TokenStream") | Represents a token stream. | Interfaces ---------- | | | | --- | --- | | *[ExpressionFunctionProviderInterface](expressionlanguage/expressionfunctionproviderinterface "Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface")* | | symfony Symfony\Component\HttpFoundation Symfony\Component\HttpFoundation ================================ Namespaces ---------- [Symfony\Component\HttpFoundation\Exception](httpfoundation/exception)[Symfony\Component\HttpFoundation\File](httpfoundation/file)[Symfony\Component\HttpFoundation\Session](httpfoundation/session) Classes ------- | | | | --- | --- | | [AcceptHeader](httpfoundation/acceptheader "Symfony\Component\HttpFoundation\AcceptHeader") | Represents an Accept-\* header. | | [AcceptHeaderItem](httpfoundation/acceptheaderitem "Symfony\Component\HttpFoundation\AcceptHeaderItem") | Represents an Accept-\* header item. | | [ApacheRequest](httpfoundation/apacherequest "Symfony\Component\HttpFoundation\ApacheRequest") | Request represents an HTTP request from an Apache server. | | [BinaryFileResponse](httpfoundation/binaryfileresponse "Symfony\Component\HttpFoundation\BinaryFileResponse") | BinaryFileResponse represents an HTTP response delivering a file. | | [Cookie](httpfoundation/cookie "Symfony\Component\HttpFoundation\Cookie") | Represents a cookie. | | [ExpressionRequestMatcher](httpfoundation/expressionrequestmatcher "Symfony\Component\HttpFoundation\ExpressionRequestMatcher") | ExpressionRequestMatcher uses an expression to match a Request. | | [FileBag](httpfoundation/filebag "Symfony\Component\HttpFoundation\FileBag") | FileBag is a container for uploaded files. | | [HeaderBag](httpfoundation/headerbag "Symfony\Component\HttpFoundation\HeaderBag") | HeaderBag is a container for HTTP headers. | | [HeaderUtils](httpfoundation/headerutils "Symfony\Component\HttpFoundation\HeaderUtils") | HTTP header utility functions. | | [IpUtils](httpfoundation/iputils "Symfony\Component\HttpFoundation\IpUtils") | Http utility functions. | | [JsonResponse](httpfoundation/jsonresponse "Symfony\Component\HttpFoundation\JsonResponse") | Response represents an HTTP response in JSON format. | | [ParameterBag](httpfoundation/parameterbag "Symfony\Component\HttpFoundation\ParameterBag") | ParameterBag is a container for key/value pairs. | | [RedirectResponse](httpfoundation/redirectresponse "Symfony\Component\HttpFoundation\RedirectResponse") | RedirectResponse represents an HTTP response doing a redirect. | | [Request](httpfoundation/request "Symfony\Component\HttpFoundation\Request") | Request represents an HTTP request. | | [RequestMatcher](httpfoundation/requestmatcher "Symfony\Component\HttpFoundation\RequestMatcher") | RequestMatcher compares a pre-defined set of checks against a Request instance. | | [RequestStack](httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") | Request stack that controls the lifecycle of requests. | | [Response](httpfoundation/response "Symfony\Component\HttpFoundation\Response") | Response represents an HTTP response. | | [ResponseHeaderBag](httpfoundation/responseheaderbag "Symfony\Component\HttpFoundation\ResponseHeaderBag") | ResponseHeaderBag is a container for Response HTTP headers. | | [ServerBag](httpfoundation/serverbag "Symfony\Component\HttpFoundation\ServerBag") | ServerBag is a container for HTTP headers from the $\_SERVER variable. | | [StreamedResponse](httpfoundation/streamedresponse "Symfony\Component\HttpFoundation\StreamedResponse") | StreamedResponse represents a streamed HTTP response. | Interfaces ---------- | | | | --- | --- | | *[RequestMatcherInterface](httpfoundation/requestmatcherinterface "Symfony\Component\HttpFoundation\RequestMatcherInterface")* | RequestMatcherInterface is an interface for strategies to match a Request. | symfony Symfony\Component\Dotenv Symfony\Component\Dotenv ======================== Namespaces ---------- [Symfony\Component\Dotenv\Exception](dotenv/exception) Classes ------- | | | | --- | --- | | [Dotenv](dotenv/dotenv "Symfony\Component\Dotenv\Dotenv") | Manages .env files. | symfony Symfony\Component\Process Symfony\Component\Process ========================= Namespaces ---------- [Symfony\Component\Process\Exception](process/exception)[Symfony\Component\Process\Pipes](process/pipes) Classes ------- | | | | --- | --- | | [ExecutableFinder](process/executablefinder "Symfony\Component\Process\ExecutableFinder") | Generic executable finder. | | [InputStream](process/inputstream "Symfony\Component\Process\InputStream") | Provides a way to continuously write to the input of a Process until the InputStream is closed. | | [PhpExecutableFinder](process/phpexecutablefinder "Symfony\Component\Process\PhpExecutableFinder") | An executable finder specifically designed for the PHP executable. | | [PhpProcess](process/phpprocess "Symfony\Component\Process\PhpProcess") | PhpProcess runs a PHP script in an independent process. | | [Process](process/process "Symfony\Component\Process\Process") | Process is a thin wrapper around proc\_\* functions to easily start independent PHP processes. | | [ProcessUtils](process/processutils "Symfony\Component\Process\ProcessUtils") | ProcessUtils is a bunch of utility methods. | symfony Symfony\Component\EventDispatcher Symfony\Component\EventDispatcher ================================= Namespaces ---------- [Symfony\Component\EventDispatcher\Debug](eventdispatcher/debug)[Symfony\Component\EventDispatcher\DependencyInjection](eventdispatcher/dependencyinjection) Classes ------- | | | | --- | --- | | [Event](eventdispatcher/event "Symfony\Component\EventDispatcher\Event") | Event is the base class for classes containing event data. | | [EventDispatcher](eventdispatcher/eventdispatcher "Symfony\Component\EventDispatcher\EventDispatcher") | The EventDispatcherInterface is the central point of Symfony's event listener system. | | [GenericEvent](eventdispatcher/genericevent "Symfony\Component\EventDispatcher\GenericEvent") | Event encapsulation class. | | [ImmutableEventDispatcher](eventdispatcher/immutableeventdispatcher "Symfony\Component\EventDispatcher\ImmutableEventDispatcher") | A read-only proxy for an event dispatcher. | Interfaces ---------- | | | | --- | --- | | *[EventDispatcherInterface](eventdispatcher/eventdispatcherinterface "Symfony\Component\EventDispatcher\EventDispatcherInterface")* | The EventDispatcherInterface is the central point of Symfony's event listener system. | | *[EventSubscriberInterface](eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface")* | An EventSubscriber knows himself what events he is interested in. |
programming_docs
symfony Symfony\Component\Stopwatch Symfony\Component\Stopwatch =========================== Classes ------- | | | | --- | --- | | [Section](stopwatch/section "Symfony\Component\Stopwatch\Section") | Stopwatch section. | | [Stopwatch](stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") | Stopwatch provides a way to profile code. | | [StopwatchEvent](stopwatch/stopwatchevent "Symfony\Component\Stopwatch\StopwatchEvent") | Represents an Event managed by Stopwatch. | | [StopwatchPeriod](stopwatch/stopwatchperiod "Symfony\Component\Stopwatch\StopwatchPeriod") | Represents an Period for an Event. | symfony Symfony\Component\Validator Symfony\Component\Validator =========================== Namespaces ---------- [Symfony\Component\Validator\Constraints](validator/constraints)[Symfony\Component\Validator\Context](validator/context)[Symfony\Component\Validator\DataCollector](validator/datacollector)[Symfony\Component\Validator\DependencyInjection](validator/dependencyinjection)[Symfony\Component\Validator\Exception](validator/exception)[Symfony\Component\Validator\Mapping](validator/mapping)[Symfony\Component\Validator\Test](validator/test)[Symfony\Component\Validator\Util](validator/util)[Symfony\Component\Validator\Validator](validator/validator)[Symfony\Component\Validator\Violation](validator/violation) Classes ------- | | | | --- | --- | | [Constraint](validator/constraint "Symfony\Component\Validator\Constraint") | Contains the properties of a constraint definition. | | [ConstraintValidator](validator/constraintvalidator "Symfony\Component\Validator\ConstraintValidator") | Base class for constraint validators. | | [ConstraintValidatorFactory](validator/constraintvalidatorfactory "Symfony\Component\Validator\ConstraintValidatorFactory") | Default implementation of the ConstraintValidatorFactoryInterface. | | [ConstraintViolation](validator/constraintviolation "Symfony\Component\Validator\ConstraintViolation") | Default implementation of {@ConstraintViolationInterface}. | | [ConstraintViolationList](validator/constraintviolationlist "Symfony\Component\Validator\ConstraintViolationList") | Default implementation of {@ConstraintViolationListInterface}. | | [ContainerConstraintValidatorFactory](validator/containerconstraintvalidatorfactory "Symfony\Component\Validator\ContainerConstraintValidatorFactory") | Uses a service container to create constraint validators. | | [Validation](validator/validation "Symfony\Component\Validator\Validation") | Entry point for the Validator component. | | [ValidatorBuilder](validator/validatorbuilder "Symfony\Component\Validator\ValidatorBuilder") | The default implementation of {@link ValidatorBuilderInterface}. | Interfaces ---------- | | | | --- | --- | | *[ConstraintValidatorFactoryInterface](validator/constraintvalidatorfactoryinterface "Symfony\Component\Validator\ConstraintValidatorFactoryInterface")* | Specifies an object able to return the correct ConstraintValidatorInterface instance given a Constraint object. | | *[ConstraintValidatorInterface](validator/constraintvalidatorinterface "Symfony\Component\Validator\ConstraintValidatorInterface")* | | | *[ConstraintViolationInterface](validator/constraintviolationinterface "Symfony\Component\Validator\ConstraintViolationInterface")* | A violation of a constraint that happened during validation. | | *[ConstraintViolationListInterface](validator/constraintviolationlistinterface "Symfony\Component\Validator\ConstraintViolationListInterface")* | A list of constraint violations. | | *[GroupSequenceProviderInterface](validator/groupsequenceproviderinterface "Symfony\Component\Validator\GroupSequenceProviderInterface")* | Defines the interface for a group sequence provider. | | *[ObjectInitializerInterface](validator/objectinitializerinterface "Symfony\Component\Validator\ObjectInitializerInterface")* | Prepares an object for validation. | | *[ValidatorBuilderInterface](validator/validatorbuilderinterface "Symfony\Component\Validator\ValidatorBuilderInterface")* | A configurable builder for ValidatorInterface objects. | symfony Symfony\Component\Translation Symfony\Component\Translation ============================= Namespaces ---------- [Symfony\Component\Translation\Catalogue](translation/catalogue)[Symfony\Component\Translation\Command](translation/command)[Symfony\Component\Translation\DataCollector](translation/datacollector)[Symfony\Component\Translation\DependencyInjection](translation/dependencyinjection)[Symfony\Component\Translation\Dumper](translation/dumper)[Symfony\Component\Translation\Exception](translation/exception)[Symfony\Component\Translation\Extractor](translation/extractor)[Symfony\Component\Translation\Formatter](translation/formatter)[Symfony\Component\Translation\Loader](translation/loader)[Symfony\Component\Translation\Reader](translation/reader)[Symfony\Component\Translation\Util](translation/util)[Symfony\Component\Translation\Writer](translation/writer) Classes ------- | | | | --- | --- | | [DataCollectorTranslator](translation/datacollectortranslator "Symfony\Component\Translation\DataCollectorTranslator") | | | [IdentityTranslator](translation/identitytranslator "Symfony\Component\Translation\IdentityTranslator") | IdentityTranslator does not translate anything. | | [Interval](translation/interval "Symfony\Component\Translation\Interval") | Tests if a given number belongs to a given math interval. | | [LoggingTranslator](translation/loggingtranslator "Symfony\Component\Translation\LoggingTranslator") | | | [MessageCatalogue](translation/messagecatalogue "Symfony\Component\Translation\MessageCatalogue") | | | [MessageSelector](translation/messageselector "Symfony\Component\Translation\MessageSelector") | MessageSelector. | | [PluralizationRules](translation/pluralizationrules "Symfony\Component\Translation\PluralizationRules") | Returns the plural rules for a given locale. | | [Translator](translation/translator "Symfony\Component\Translation\Translator") | | Interfaces ---------- | | | | --- | --- | | *[MessageCatalogueInterface](translation/messagecatalogueinterface "Symfony\Component\Translation\MessageCatalogueInterface")* | MessageCatalogueInterface. | | *[MetadataAwareInterface](translation/metadataawareinterface "Symfony\Component\Translation\MetadataAwareInterface")* | MetadataAwareInterface. | | *[TranslatorBagInterface](translation/translatorbaginterface "Symfony\Component\Translation\TranslatorBagInterface")* | TranslatorBagInterface. | | *[TranslatorInterface](translation/translatorinterface "Symfony\Component\Translation\TranslatorInterface")* | TranslatorInterface. | symfony Symfony\Component\Cache Symfony\Component\Cache ======================= Namespaces ---------- [Symfony\Component\Cache\Adapter](cache/adapter)[Symfony\Component\Cache\DataCollector](cache/datacollector)[Symfony\Component\Cache\Exception](cache/exception)[Symfony\Component\Cache\Simple](cache/simple)[Symfony\Component\Cache\Traits](cache/traits) Classes ------- | | | | --- | --- | | [CacheItem](cache/cacheitem "Symfony\Component\Cache\CacheItem") | | | [DoctrineProvider](cache/doctrineprovider "Symfony\Component\Cache\DoctrineProvider") | | Interfaces ---------- | | | | --- | --- | | *[PruneableInterface](cache/pruneableinterface "Symfony\Component\Cache\PruneableInterface")* | Interface extends psr-6 and psr-16 caches to allow for pruning (deletion) of all expired cache items. | | *[ResettableInterface](cache/resettableinterface "Symfony\Component\Cache\ResettableInterface")* | Resets a pool's local state. | symfony Symfony\Component\Yaml Symfony\Component\Yaml ====================== Namespaces ---------- [Symfony\Component\Yaml\Command](yaml/command)[Symfony\Component\Yaml\Exception](yaml/exception)[Symfony\Component\Yaml\Tag](yaml/tag) Classes ------- | | | | --- | --- | | [Dumper](yaml/dumper "Symfony\Component\Yaml\Dumper") | Dumper dumps PHP variables to YAML strings. | | [Escaper](yaml/escaper "Symfony\Component\Yaml\Escaper") | Escaper encapsulates escaping rules for single and double-quoted YAML strings. | | [Inline](yaml/inline "Symfony\Component\Yaml\Inline") | Inline implements a YAML parser/dumper for the YAML inline syntax. | | [Parser](yaml/parser "Symfony\Component\Yaml\Parser") | Parser parses YAML strings to convert them to PHP arrays. | | [Unescaper](yaml/unescaper "Symfony\Component\Yaml\Unescaper") | Unescaper encapsulates unescaping rules for single and double-quoted YAML strings. | | [Yaml](yaml/yaml "Symfony\Component\Yaml\Yaml") | Yaml offers convenience methods to load and dump YAML. | symfony Symfony\Component\CssSelector Symfony\Component\CssSelector ============================= Namespaces ---------- [Symfony\Component\CssSelector\Exception](cssselector/exception)[Symfony\Component\CssSelector\Node](cssselector/node)[Symfony\Component\CssSelector\Parser](cssselector/parser)[Symfony\Component\CssSelector\XPath](cssselector/xpath) Classes ------- | | | | --- | --- | | [CssSelectorConverter](cssselector/cssselectorconverter "Symfony\Component\CssSelector\CssSelectorConverter") | CssSelectorConverter is the main entry point of the component and can convert CSS selectors to XPath expressions. | symfony Symfony\Component\PropertyInfo Symfony\Component\PropertyInfo ============================== Namespaces ---------- [Symfony\Component\PropertyInfo\DependencyInjection](propertyinfo/dependencyinjection)[Symfony\Component\PropertyInfo\Extractor](propertyinfo/extractor)[Symfony\Component\PropertyInfo\Util](propertyinfo/util) Classes ------- | | | | --- | --- | | [PropertyInfoCacheExtractor](propertyinfo/propertyinfocacheextractor "Symfony\Component\PropertyInfo\PropertyInfoCacheExtractor") | Adds a PSR-6 cache layer on top of an extractor. | | [PropertyInfoExtractor](propertyinfo/propertyinfoextractor "Symfony\Component\PropertyInfo\PropertyInfoExtractor") | Default {see PropertyInfoExtractorInterface} implementation. | | [Type](propertyinfo/type "Symfony\Component\PropertyInfo\Type") | Type value object (immutable). | Interfaces ---------- | | | | --- | --- | | *[PropertyAccessExtractorInterface](propertyinfo/propertyaccessextractorinterface "Symfony\Component\PropertyInfo\PropertyAccessExtractorInterface")* | Guesses if the property can be accessed or mutated. | | *[PropertyDescriptionExtractorInterface](propertyinfo/propertydescriptionextractorinterface "Symfony\Component\PropertyInfo\PropertyDescriptionExtractorInterface")* | Guesses the property's human readable description. | | *[PropertyInfoExtractorInterface](propertyinfo/propertyinfoextractorinterface "Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface")* | Gets info about PHP class properties. | | *[PropertyListExtractorInterface](propertyinfo/propertylistextractorinterface "Symfony\Component\PropertyInfo\PropertyListExtractorInterface")* | Extracts the list of properties available for the given class. | | *[PropertyTypeExtractorInterface](propertyinfo/propertytypeextractorinterface "Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface")* | Type Extractor Interface. | symfony Symfony\Component\Messenger Symfony\Component\Messenger =========================== Namespaces ---------- [Symfony\Component\Messenger\Asynchronous](messenger/asynchronous)[Symfony\Component\Messenger\Command](messenger/command)[Symfony\Component\Messenger\DataCollector](messenger/datacollector)[Symfony\Component\Messenger\DependencyInjection](messenger/dependencyinjection)[Symfony\Component\Messenger\Exception](messenger/exception)[Symfony\Component\Messenger\Handler](messenger/handler)[Symfony\Component\Messenger\Middleware](messenger/middleware)[Symfony\Component\Messenger\Transport](messenger/transport) Classes ------- | | | | --- | --- | | [Envelope](messenger/envelope "Symfony\Component\Messenger\Envelope") | A message wrapped in an envelope with items (configurations, markers, . | | [MessageBus](messenger/messagebus "Symfony\Component\Messenger\MessageBus") | | | [TraceableMessageBus](messenger/traceablemessagebus "Symfony\Component\Messenger\TraceableMessageBus") | | | [Worker](messenger/worker "Symfony\Component\Messenger\Worker") | | Interfaces ---------- | | | | --- | --- | | *[EnvelopeAwareInterface](messenger/envelopeawareinterface "Symfony\Component\Messenger\EnvelopeAwareInterface")* | A Messenger protagonist aware of the message envelope and its content. | | *[EnvelopeItemInterface](messenger/envelopeiteminterface "Symfony\Component\Messenger\EnvelopeItemInterface")* | An envelope item related to a message. | | *[MessageBusInterface](messenger/messagebusinterface "Symfony\Component\Messenger\MessageBusInterface")* | | symfony Symfony\Component\BrowserKit Symfony\Component\BrowserKit ============================ Namespaces ---------- [Symfony\Component\BrowserKit\Exception](browserkit/exception) Classes ------- | | | | --- | --- | | [Client](browserkit/client "Symfony\Component\BrowserKit\Client") | Client simulates a browser. | | [Cookie](browserkit/cookie "Symfony\Component\BrowserKit\Cookie") | Cookie represents an HTTP cookie. | | [CookieJar](browserkit/cookiejar "Symfony\Component\BrowserKit\CookieJar") | CookieJar. | | [History](browserkit/history "Symfony\Component\BrowserKit\History") | History. | | [Request](browserkit/request "Symfony\Component\BrowserKit\Request") | | | [Response](browserkit/response "Symfony\Component\BrowserKit\Response") | | symfony Symfony\Component\Security Symfony\Component\Security ========================== Namespaces ---------- [Symfony\Component\Security\Core](security/core)[Symfony\Component\Security\Csrf](security/csrf)[Symfony\Component\Security\Guard](security/guard)[Symfony\Component\Security\Http](security/http) symfony Symfony\Component\Templating Symfony\Component\Templating ============================ Namespaces ---------- [Symfony\Component\Templating\Helper](templating/helper)[Symfony\Component\Templating\Loader](templating/loader)[Symfony\Component\Templating\Storage](templating/storage) Classes ------- | | | | --- | --- | | [DelegatingEngine](templating/delegatingengine "Symfony\Component\Templating\DelegatingEngine") | DelegatingEngine selects an engine for a given template. | | [PhpEngine](templating/phpengine "Symfony\Component\Templating\PhpEngine") | PhpEngine is an engine able to render PHP templates. | | [TemplateNameParser](templating/templatenameparser "Symfony\Component\Templating\TemplateNameParser") | TemplateNameParser is the default implementation of TemplateNameParserInterface. | | [TemplateReference](templating/templatereference "Symfony\Component\Templating\TemplateReference") | Internal representation of a template. | Interfaces ---------- | | | | --- | --- | | *[EngineInterface](templating/engineinterface "Symfony\Component\Templating\EngineInterface")* | EngineInterface is the interface each engine must implement. | | *[StreamingEngineInterface](templating/streamingengineinterface "Symfony\Component\Templating\StreamingEngineInterface")* | StreamingEngineInterface provides a method that knows how to stream a template. | | *[TemplateNameParserInterface](templating/templatenameparserinterface "Symfony\Component\Templating\TemplateNameParserInterface")* | TemplateNameParserInterface converts template names to TemplateReferenceInterface instances. | | *[TemplateReferenceInterface](templating/templatereferenceinterface "Symfony\Component\Templating\TemplateReferenceInterface")* | Interface to be implemented by all templates. | symfony Symfony\Component\DependencyInjection Symfony\Component\DependencyInjection ===================================== Namespaces ---------- [Symfony\Component\DependencyInjection\Argument](dependencyinjection/argument)[Symfony\Component\DependencyInjection\Compiler](dependencyinjection/compiler)[Symfony\Component\DependencyInjection\Config](dependencyinjection/config)[Symfony\Component\DependencyInjection\Dumper](dependencyinjection/dumper)[Symfony\Component\DependencyInjection\Exception](dependencyinjection/exception)[Symfony\Component\DependencyInjection\Extension](dependencyinjection/extension)[Symfony\Component\DependencyInjection\LazyProxy](dependencyinjection/lazyproxy)[Symfony\Component\DependencyInjection\Loader](dependencyinjection/loader)[Symfony\Component\DependencyInjection\ParameterBag](dependencyinjection/parameterbag) Classes ------- | | | | --- | --- | | [Alias](dependencyinjection/alias "Symfony\Component\DependencyInjection\Alias") | | | [ChildDefinition](dependencyinjection/childdefinition "Symfony\Component\DependencyInjection\ChildDefinition") | This definition extends another definition. | | [Container](dependencyinjection/container "Symfony\Component\DependencyInjection\Container") | Container is a dependency injection container. | | [ContainerAwareTrait](dependencyinjection/containerawaretrait "Symfony\Component\DependencyInjection\ContainerAwareTrait") | ContainerAware trait. | | [ContainerBuilder](dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | ContainerBuilder is a DI container that provides an API to easily describe services. | | [Definition](dependencyinjection/definition "Symfony\Component\DependencyInjection\Definition") | Definition represents a service definition. | | [EnvVarProcessor](dependencyinjection/envvarprocessor "Symfony\Component\DependencyInjection\EnvVarProcessor") | | | [ExpressionLanguage](dependencyinjection/expressionlanguage "Symfony\Component\DependencyInjection\ExpressionLanguage") | Adds some function to the default ExpressionLanguage. | | [ExpressionLanguageProvider](dependencyinjection/expressionlanguageprovider "Symfony\Component\DependencyInjection\ExpressionLanguageProvider") | Define some ExpressionLanguage functions. | | [Parameter](dependencyinjection/parameter "Symfony\Component\DependencyInjection\Parameter") | Parameter represents a parameter reference. | | [Reference](dependencyinjection/reference "Symfony\Component\DependencyInjection\Reference") | Reference represents a service reference. | | [ServiceLocator](dependencyinjection/servicelocator "Symfony\Component\DependencyInjection\ServiceLocator") | | | [TypedReference](dependencyinjection/typedreference "Symfony\Component\DependencyInjection\TypedReference") | Represents a PHP type-hinted service reference. | | [Variable](dependencyinjection/variable "Symfony\Component\DependencyInjection\Variable") | Represents a variable. | Interfaces ---------- | | | | --- | --- | | *[ContainerAwareInterface](dependencyinjection/containerawareinterface "Symfony\Component\DependencyInjection\ContainerAwareInterface")* | ContainerAwareInterface should be implemented by classes that depends on a Container. | | *[ContainerInterface](dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface")* | ContainerInterface is the interface implemented by service container classes. | | *[EnvVarProcessorInterface](dependencyinjection/envvarprocessorinterface "Symfony\Component\DependencyInjection\EnvVarProcessorInterface")* | The EnvVarProcessorInterface is implemented by objects that manage environment-like variables. | | *[ResettableContainerInterface](dependencyinjection/resettablecontainerinterface "Symfony\Component\DependencyInjection\ResettableContainerInterface")* | ResettableContainerInterface defines additional resetting functionality for containers, allowing to release shared services when the container is not needed anymore. | | *[ServiceSubscriberInterface](dependencyinjection/servicesubscriberinterface "Symfony\Component\DependencyInjection\ServiceSubscriberInterface")* | A ServiceSubscriber exposes its dependencies via the static {@link getSubscribedServices} method. | | *[TaggedContainerInterface](dependencyinjection/taggedcontainerinterface "Symfony\Component\DependencyInjection\TaggedContainerInterface")* | TaggedContainerInterface is the interface implemented when a container knows how to deals with tags. |
programming_docs
symfony Symfony\Component\PropertyAccess Symfony\Component\PropertyAccess ================================ Namespaces ---------- [Symfony\Component\PropertyAccess\Exception](propertyaccess/exception) Classes ------- | | | | --- | --- | | [PropertyAccess](propertyaccess/propertyaccess "Symfony\Component\PropertyAccess\PropertyAccess") | Entry point of the PropertyAccess component. | | [PropertyAccessor](propertyaccess/propertyaccessor "Symfony\Component\PropertyAccess\PropertyAccessor") | Default implementation of {@link PropertyAccessorInterface}. | | [PropertyAccessorBuilder](propertyaccess/propertyaccessorbuilder "Symfony\Component\PropertyAccess\PropertyAccessorBuilder") | A configurable builder to create a PropertyAccessor. | | [PropertyPath](propertyaccess/propertypath "Symfony\Component\PropertyAccess\PropertyPath") | Default implementation of {@link PropertyPathInterface}. | | [PropertyPathBuilder](propertyaccess/propertypathbuilder "Symfony\Component\PropertyAccess\PropertyPathBuilder") | | | [PropertyPathIterator](propertyaccess/propertypathiterator "Symfony\Component\PropertyAccess\PropertyPathIterator") | Traverses a property path and provides additional methods to find out information about the current element. | Interfaces ---------- | | | | --- | --- | | *[PropertyAccessorInterface](propertyaccess/propertyaccessorinterface "Symfony\Component\PropertyAccess\PropertyAccessorInterface")* | Writes and reads values to/from an object/array graph. | | *[PropertyPathInterface](propertyaccess/propertypathinterface "Symfony\Component\PropertyAccess\PropertyPathInterface")* | A sequence of property names or array indices. | | *[PropertyPathIteratorInterface](propertyaccess/propertypathiteratorinterface "Symfony\Component\PropertyAccess\PropertyPathIteratorInterface")* | | symfony Symfony\Component\Console Symfony\Component\Console ========================= Namespaces ---------- [Symfony\Component\Console\Command](console/command)[Symfony\Component\Console\CommandLoader](console/commandloader)[Symfony\Component\Console\DependencyInjection](console/dependencyinjection)[Symfony\Component\Console\Descriptor](console/descriptor)[Symfony\Component\Console\Event](console/event)[Symfony\Component\Console\EventListener](console/eventlistener)[Symfony\Component\Console\Exception](console/exception)[Symfony\Component\Console\Formatter](console/formatter)[Symfony\Component\Console\Helper](console/helper)[Symfony\Component\Console\Input](console/input)[Symfony\Component\Console\Logger](console/logger)[Symfony\Component\Console\Output](console/output)[Symfony\Component\Console\Question](console/question)[Symfony\Component\Console\Style](console/style)[Symfony\Component\Console\Tester](console/tester) Classes ------- | | | | --- | --- | | [Application](console/application "Symfony\Component\Console\Application") | An Application is the container for a collection of commands. | | [ConsoleEvents](console/consoleevents "Symfony\Component\Console\ConsoleEvents") | Contains all events dispatched by an Application. | | [Terminal](console/terminal "Symfony\Component\Console\Terminal") | | symfony Symfony\Component\Config Symfony\Component\Config ======================== Namespaces ---------- [Symfony\Component\Config\Definition](config/definition)[Symfony\Component\Config\Exception](config/exception)[Symfony\Component\Config\Loader](config/loader)[Symfony\Component\Config\Resource](config/resource)[Symfony\Component\Config\Util](config/util) Classes ------- | | | | --- | --- | | [ConfigCache](config/configcache "Symfony\Component\Config\ConfigCache") | ConfigCache caches arbitrary content in files on disk. | | [ConfigCacheFactory](config/configcachefactory "Symfony\Component\Config\ConfigCacheFactory") | Basic implementation of ConfigCacheFactoryInterface that creates an instance of the default ConfigCache. | | [FileLocator](config/filelocator "Symfony\Component\Config\FileLocator") | FileLocator uses an array of pre-defined paths to find files. | | [ResourceCheckerConfigCache](config/resourcecheckerconfigcache "Symfony\Component\Config\ResourceCheckerConfigCache") | ResourceCheckerConfigCache uses instances of ResourceCheckerInterface to check whether cached data is still fresh. | | [ResourceCheckerConfigCacheFactory](config/resourcecheckerconfigcachefactory "Symfony\Component\Config\ResourceCheckerConfigCacheFactory") | A ConfigCacheFactory implementation that validates the cache with an arbitrary set of ResourceCheckers. | Interfaces ---------- | | | | --- | --- | | *[ConfigCacheFactoryInterface](config/configcachefactoryinterface "Symfony\Component\Config\ConfigCacheFactoryInterface")* | Interface for a ConfigCache factory. This factory creates an instance of ConfigCacheInterface and initializes the cache if necessary. | | *[ConfigCacheInterface](config/configcacheinterface "Symfony\Component\Config\ConfigCacheInterface")* | Interface for ConfigCache. | | *[FileLocatorInterface](config/filelocatorinterface "Symfony\Component\Config\FileLocatorInterface")* | | | *[ResourceCheckerInterface](config/resourcecheckerinterface "Symfony\Component\Config\ResourceCheckerInterface")* | Interface for ResourceCheckers. | symfony Symfony\Component\Debug Symfony\Component\Debug ======================= Namespaces ---------- [Symfony\Component\Debug\Exception](debug/exception)[Symfony\Component\Debug\FatalErrorHandler](debug/fatalerrorhandler) Classes ------- | | | | --- | --- | | [BufferingLogger](debug/bufferinglogger "Symfony\Component\Debug\BufferingLogger") | A buffering logger that stacks logs for later. | | [Debug](debug/debug "Symfony\Component\Debug\Debug") | Registers all the debug tools. | | [DebugClassLoader](debug/debugclassloader "Symfony\Component\Debug\DebugClassLoader") | Autoloader checking if the class is really defined in the file found. | | [ErrorHandler](debug/errorhandler "Symfony\Component\Debug\ErrorHandler") | A generic ErrorHandler for the PHP engine. | | [ExceptionHandler](debug/exceptionhandler "Symfony\Component\Debug\ExceptionHandler") | ExceptionHandler converts an exception to a Response object. | symfony Symfony\Component\Lock Symfony\Component\Lock ====================== Namespaces ---------- [Symfony\Component\Lock\Exception](lock/exception)[Symfony\Component\Lock\Store](lock/store)[Symfony\Component\Lock\Strategy](lock/strategy) Classes ------- | | | | --- | --- | | [Factory](lock/factory "Symfony\Component\Lock\Factory") | Factory provides method to create locks. | | [Key](lock/key "Symfony\Component\Lock\Key") | Key is a container for the state of the locks in stores. | | [Lock](lock/lock "Symfony\Component\Lock\Lock") | Lock is the default implementation of the LockInterface. | Interfaces ---------- | | | | --- | --- | | *[LockInterface](lock/lockinterface "Symfony\Component\Lock\LockInterface")* | LockInterface defines an interface to manipulate the status of a lock. | | *[StoreInterface](lock/storeinterface "Symfony\Component\Lock\StoreInterface")* | StoreInterface defines an interface to manipulate a lock store. | symfony Symfony\Component\Serializer Symfony\Component\Serializer ============================ Namespaces ---------- [Symfony\Component\Serializer\Annotation](serializer/annotation)[Symfony\Component\Serializer\DependencyInjection](serializer/dependencyinjection)[Symfony\Component\Serializer\Encoder](serializer/encoder)[Symfony\Component\Serializer\Exception](serializer/exception)[Symfony\Component\Serializer\Mapping](serializer/mapping)[Symfony\Component\Serializer\NameConverter](serializer/nameconverter)[Symfony\Component\Serializer\Normalizer](serializer/normalizer) Classes ------- | | | | --- | --- | | [Serializer](serializer/serializer "Symfony\Component\Serializer\Serializer") | Serializer serializes and deserializes data. | | [SerializerAwareTrait](serializer/serializerawaretrait "Symfony\Component\Serializer\SerializerAwareTrait") | SerializerAware trait. | Interfaces ---------- | | | | --- | --- | | *[SerializerAwareInterface](serializer/serializerawareinterface "Symfony\Component\Serializer\SerializerAwareInterface")* | Defines the interface of encoders. | | *[SerializerInterface](serializer/serializerinterface "Symfony\Component\Serializer\SerializerInterface")* | Defines the interface of the Serializer. | symfony Symfony\Component\Ldap Symfony\Component\Ldap ====================== Namespaces ---------- [Symfony\Component\Ldap\Adapter](ldap/adapter)[Symfony\Component\Ldap\Exception](ldap/exception) Classes ------- | | | | --- | --- | | [Entry](ldap/entry "Symfony\Component\Ldap\Entry") | | | [Ldap](ldap/ldap "Symfony\Component\Ldap\Ldap") | | Interfaces ---------- | | | | --- | --- | | *[LdapInterface](ldap/ldapinterface "Symfony\Component\Ldap\LdapInterface")* | Ldap interface. | symfony Symfony\Component\VarDumper Symfony\Component\VarDumper =========================== Namespaces ---------- [Symfony\Component\VarDumper\Caster](vardumper/caster)[Symfony\Component\VarDumper\Cloner](vardumper/cloner)[Symfony\Component\VarDumper\Command](vardumper/command)[Symfony\Component\VarDumper\Dumper](vardumper/dumper)[Symfony\Component\VarDumper\Exception](vardumper/exception)[Symfony\Component\VarDumper\Server](vardumper/server)[Symfony\Component\VarDumper\Test](vardumper/test) Classes ------- | | | | --- | --- | | [VarDumper](vardumper/vardumper "Symfony\Component\VarDumper\VarDumper") | | symfony Symfony\Component\OptionsResolver Symfony\Component\OptionsResolver ================================= Namespaces ---------- [Symfony\Component\OptionsResolver\Debug](optionsresolver/debug)[Symfony\Component\OptionsResolver\Exception](optionsresolver/exception) Classes ------- | | | | --- | --- | | [OptionsResolver](optionsresolver/optionsresolver "Symfony\Component\OptionsResolver\OptionsResolver") | Validates options and merges them with default values. | Interfaces ---------- | | | | --- | --- | | *[Options](optionsresolver/options "Symfony\Component\OptionsResolver\Options")* | Contains resolved option values. | symfony Symfony\Component\Finder Symfony\Component\Finder ======================== Namespaces ---------- [Symfony\Component\Finder\Comparator](finder/comparator)[Symfony\Component\Finder\Exception](finder/exception)[Symfony\Component\Finder\Iterator](finder/iterator) Classes ------- | | | | --- | --- | | [Finder](finder/finder "Symfony\Component\Finder\Finder") | Finder allows to build rules to find files and directories. | | [Glob](finder/glob "Symfony\Component\Finder\Glob") | Glob matches globbing patterns against text. | | [SplFileInfo](finder/splfileinfo "Symfony\Component\Finder\SplFileInfo") | Extends \SplFileInfo to support relative paths. | symfony Symfony\Component\Inflector Symfony\Component\Inflector =========================== Classes ------- | | | | --- | --- | | [Inflector](inflector/inflector "Symfony\Component\Inflector\Inflector") | Converts words between singular and plural forms. | symfony Symfony\Component\Workflow Symfony\Component\Workflow ========================== Namespaces ---------- [Symfony\Component\Workflow\DependencyInjection](workflow/dependencyinjection)[Symfony\Component\Workflow\Dumper](workflow/dumper)[Symfony\Component\Workflow\Event](workflow/event)[Symfony\Component\Workflow\EventListener](workflow/eventlistener)[Symfony\Component\Workflow\Exception](workflow/exception)[Symfony\Component\Workflow\MarkingStore](workflow/markingstore)[Symfony\Component\Workflow\Metadata](workflow/metadata)[Symfony\Component\Workflow\SupportStrategy](workflow/supportstrategy)[Symfony\Component\Workflow\Validator](workflow/validator) Classes ------- | | | | --- | --- | | [Definition](workflow/definition "Symfony\Component\Workflow\Definition") | | | [DefinitionBuilder](workflow/definitionbuilder "Symfony\Component\Workflow\DefinitionBuilder") | Builds a definition. | | [Marking](workflow/marking "Symfony\Component\Workflow\Marking") | Marking contains the place of every tokens. | | [Registry](workflow/registry "Symfony\Component\Workflow\Registry") | | | [StateMachine](workflow/statemachine "Symfony\Component\Workflow\StateMachine") | | | [Transition](workflow/transition "Symfony\Component\Workflow\Transition") | | | [TransitionBlocker](workflow/transitionblocker "Symfony\Component\Workflow\TransitionBlocker") | A reason why a transition cannot be performed for a subject. | | [TransitionBlockerList](workflow/transitionblockerlist "Symfony\Component\Workflow\TransitionBlockerList") | A list of transition blockers. | | [Workflow](workflow/workflow "Symfony\Component\Workflow\Workflow") | | Interfaces ---------- | | | | --- | --- | | *[WorkflowInterface](workflow/workflowinterface "Symfony\Component\Workflow\WorkflowInterface")* | | symfony HttpKernel HttpKernel =========== class **HttpKernel** implements [HttpKernelInterface](httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface"), [TerminableInterface](terminableinterface "Symfony\Component\HttpKernel\TerminableInterface") HttpKernel notifies events to convert a Request object to a Response one. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $dispatcher | | | | protected | $resolver | | | | protected | $requestStack | | | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([EventDispatcherInterface](../eventdispatcher/eventdispatcherinterface "Symfony\Component\EventDispatcher\EventDispatcherInterface") $dispatcher, [ControllerResolverInterface](controller/controllerresolverinterface "Symfony\Component\HttpKernel\Controller\ControllerResolverInterface") $resolver, [RequestStack](../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack = null, [ArgumentResolverInterface](controller/argumentresolverinterface "Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface") $argumentResolver = null) | | | [Response](../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [handle](#method_handle)([Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int $type = HttpKernelInterface::MASTER\_REQUEST, bool $catch = true) Handles a Request to convert it to a Response. | | | | [terminate](#method_terminate)([Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Terminates a request/response cycle. | | | | [terminateWithException](#method_terminateWithException)([Exception](http://php.net/Exception) $exception, [Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request = null) | | Details ------- ### \_\_construct([EventDispatcherInterface](../eventdispatcher/eventdispatcherinterface "Symfony\Component\EventDispatcher\EventDispatcherInterface") $dispatcher, [ControllerResolverInterface](controller/controllerresolverinterface "Symfony\Component\HttpKernel\Controller\ControllerResolverInterface") $resolver, [RequestStack](../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack = null, [ArgumentResolverInterface](controller/argumentresolverinterface "Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface") $argumentResolver = null) #### Parameters | | | | | --- | --- | --- | | [EventDispatcherInterface](../eventdispatcher/eventdispatcherinterface "Symfony\Component\EventDispatcher\EventDispatcherInterface") | $dispatcher | | | [ControllerResolverInterface](controller/controllerresolverinterface "Symfony\Component\HttpKernel\Controller\ControllerResolverInterface") | $resolver | | | [RequestStack](../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") | $requestStack | | | [ArgumentResolverInterface](controller/argumentresolverinterface "Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface") | $argumentResolver | | ### [Response](../httpfoundation/response "Symfony\Component\HttpFoundation\Response") handle([Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int $type = HttpKernelInterface::MASTER\_REQUEST, bool $catch = true) Handles a Request to convert it to a Response. When $catch is true, the implementation must catch all exceptions and do its best to convert them to a Response instance. #### Parameters | | | | | --- | --- | --- | | [Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | int | $type | The type of the request (one of HttpKernelInterface::MASTER\_REQUEST or HttpKernelInterface::SUB\_REQUEST) | | bool | $catch | Whether to catch exceptions or not | #### Return Value | | | | --- | --- | | [Response](../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | A Response instance | #### Exceptions | | | | --- | --- | | [Exception](http://php.net/Exception) | When an Exception occurs during processing | ### terminate([Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Terminates a request/response cycle. Should be called after sending the response and before shutting down the kernel. #### Parameters | | | | | --- | --- | --- | | [Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | ### terminateWithException([Exception](http://php.net/Exception) $exception, [Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request = null) #### Parameters | | | | | --- | --- | --- | | [Exception](http://php.net/Exception) | $exception | | | [Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | symfony Client Client ======= class **Client** extends [Client](../browserkit/client "Symfony\Component\BrowserKit\Client") Client simulates a browser and makes requests to a Kernel object. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $history | | from [Client](../browserkit/client#property_history "Symfony\Component\BrowserKit\Client") | | protected | $cookieJar | | from [Client](../browserkit/client#property_cookieJar "Symfony\Component\BrowserKit\Client") | | protected | $server | | from [Client](../browserkit/client#property_server "Symfony\Component\BrowserKit\Client") | | protected | $internalRequest | | from [Client](../browserkit/client#property_internalRequest "Symfony\Component\BrowserKit\Client") | | protected | $request | | from [Client](../browserkit/client#property_request "Symfony\Component\BrowserKit\Client") | | protected | $internalResponse | | from [Client](../browserkit/client#property_internalResponse "Symfony\Component\BrowserKit\Client") | | protected | $response | | from [Client](../browserkit/client#property_response "Symfony\Component\BrowserKit\Client") | | protected | $crawler | | from [Client](../browserkit/client#property_crawler "Symfony\Component\BrowserKit\Client") | | protected | $insulated | | from [Client](../browserkit/client#property_insulated "Symfony\Component\BrowserKit\Client") | | protected | $redirect | | from [Client](../browserkit/client#property_redirect "Symfony\Component\BrowserKit\Client") | | protected | $followRedirects | | from [Client](../browserkit/client#property_followRedirects "Symfony\Component\BrowserKit\Client") | | protected | $kernel | | | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([HttpKernelInterface](httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, array $server = array(), [History](../browserkit/history "Symfony\Component\BrowserKit\History") $history = null, [CookieJar](../browserkit/cookiejar "Symfony\Component\BrowserKit\CookieJar") $cookieJar = null) | | | | [followRedirects](#method_followRedirects)(bool $followRedirect = true) Sets whether to automatically follow redirects or not. | from [Client](../browserkit/client#method_followRedirects "Symfony\Component\BrowserKit\Client") | | bool | [isFollowingRedirects](#method_isFollowingRedirects)() Returns whether client automatically follows redirects or not. | from [Client](../browserkit/client#method_isFollowingRedirects "Symfony\Component\BrowserKit\Client") | | | [setMaxRedirects](#method_setMaxRedirects)(int $maxRedirects) Sets the maximum number of redirects that crawler can follow. | from [Client](../browserkit/client#method_setMaxRedirects "Symfony\Component\BrowserKit\Client") | | int | [getMaxRedirects](#method_getMaxRedirects)() Returns the maximum number of redirects that crawler can follow. | from [Client](../browserkit/client#method_getMaxRedirects "Symfony\Component\BrowserKit\Client") | | | [insulate](#method_insulate)(bool $insulated = true) Sets the insulated flag. | from [Client](../browserkit/client#method_insulate "Symfony\Component\BrowserKit\Client") | | | [setServerParameters](#method_setServerParameters)(array $server) Sets server parameters. | from [Client](../browserkit/client#method_setServerParameters "Symfony\Component\BrowserKit\Client") | | | [setServerParameter](#method_setServerParameter)(string $key, string $value) Sets single server parameter. | from [Client](../browserkit/client#method_setServerParameter "Symfony\Component\BrowserKit\Client") | | string | [getServerParameter](#method_getServerParameter)(string $key, string $default = '') Gets single server parameter for specified key. | from [Client](../browserkit/client#method_getServerParameter "Symfony\Component\BrowserKit\Client") | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") | [xmlHttpRequest](#method_xmlHttpRequest)(string $method, string $uri, array $parameters = array(), array $files = array(), array $server = array(), string $content = null, bool $changeHistory = true) | from [Client](../browserkit/client#method_xmlHttpRequest "Symfony\Component\BrowserKit\Client") | | [History](../browserkit/history "Symfony\Component\BrowserKit\History") | [getHistory](#method_getHistory)() Returns the History instance. | from [Client](../browserkit/client#method_getHistory "Symfony\Component\BrowserKit\Client") | | [CookieJar](../browserkit/cookiejar "Symfony\Component\BrowserKit\CookieJar") | [getCookieJar](#method_getCookieJar)() Returns the CookieJar instance. | from [Client](../browserkit/client#method_getCookieJar "Symfony\Component\BrowserKit\Client") | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") | [getCrawler](#method_getCrawler)() Returns the current Crawler instance. | from [Client](../browserkit/client#method_getCrawler "Symfony\Component\BrowserKit\Client") | | [Response](../browserkit/response "Symfony\Component\BrowserKit\Response") | [getInternalResponse](#method_getInternalResponse)() Returns the current BrowserKit Response instance. | from [Client](../browserkit/client#method_getInternalResponse "Symfony\Component\BrowserKit\Client") | | Response | [getResponse](#method_getResponse)() A Response instance | | | [Request](../browserkit/request "Symfony\Component\BrowserKit\Request") | [getInternalRequest](#method_getInternalRequest)() Returns the current BrowserKit Request instance. | from [Client](../browserkit/client#method_getInternalRequest "Symfony\Component\BrowserKit\Client") | | Request | [getRequest](#method_getRequest)() A Request instance | | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") | [click](#method_click)([Link](../domcrawler/link "Symfony\Component\DomCrawler\Link") $link) Clicks on a given link. | from [Client](../browserkit/client#method_click "Symfony\Component\BrowserKit\Client") | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") | [submit](#method_submit)([Form](../domcrawler/form "Symfony\Component\DomCrawler\Form") $form, array $values = array()) Submits a form. | from [Client](../browserkit/client#method_submit "Symfony\Component\BrowserKit\Client") | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") | [request](#method_request)(string $method, string $uri, array $parameters = array(), array $files = array(), array $server = array(), string $content = null, bool $changeHistory = true) Calls a URI. | from [Client](../browserkit/client#method_request "Symfony\Component\BrowserKit\Client") | | object | [doRequestInProcess](#method_doRequestInProcess)(object $request) Makes a request in another process. | from [Client](../browserkit/client#method_doRequestInProcess "Symfony\Component\BrowserKit\Client") | | object | [doRequest](#method_doRequest)(object $request) Makes a request. | | | | [getScript](#method_getScript)(object $request) Returns the script to execute when the request must be insulated. | | | object | [filterRequest](#method_filterRequest)([Request](../browserkit/request "Symfony\Component\BrowserKit\Request") $request) Converts the BrowserKit request to a HttpKernel request. | | | [Response](../browserkit/response "Symfony\Component\BrowserKit\Response") | [filterResponse](#method_filterResponse)(object $response) Converts the HttpKernel response to a BrowserKit response. | | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler")|null | [createCrawlerFromContent](#method_createCrawlerFromContent)(string $uri, string $content, string $type) Creates a crawler. | from [Client](../browserkit/client#method_createCrawlerFromContent "Symfony\Component\BrowserKit\Client") | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") | [back](#method_back)() Goes back in the browser history. | from [Client](../browserkit/client#method_back "Symfony\Component\BrowserKit\Client") | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") | [forward](#method_forward)() Goes forward in the browser history. | from [Client](../browserkit/client#method_forward "Symfony\Component\BrowserKit\Client") | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") | [reload](#method_reload)() Reloads the current browser. | from [Client](../browserkit/client#method_reload "Symfony\Component\BrowserKit\Client") | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") | [followRedirect](#method_followRedirect)() Follow redirects? | from [Client](../browserkit/client#method_followRedirect "Symfony\Component\BrowserKit\Client") | | | [restart](#method_restart)() Restarts the client. | from [Client](../browserkit/client#method_restart "Symfony\Component\BrowserKit\Client") | | string | [getAbsoluteUri](#method_getAbsoluteUri)(string $uri) Takes a URI and converts it to absolute if it is not already absolute. | from [Client](../browserkit/client#method_getAbsoluteUri "Symfony\Component\BrowserKit\Client") | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") | [requestFromRequest](#method_requestFromRequest)([Request](../browserkit/request "Symfony\Component\BrowserKit\Request") $request, bool $changeHistory = true) Makes a request from a Request object directly. | from [Client](../browserkit/client#method_requestFromRequest "Symfony\Component\BrowserKit\Client") | | | [catchExceptions](#method_catchExceptions)(bool $catchExceptions) Sets whether to catch exceptions when the kernel is handling a request. | | | | [getHandleScript](#method_getHandleScript)() | | | array | [filterFiles](#method_filterFiles)(array $files) Filters an array of files. | | Details ------- ### \_\_construct([HttpKernelInterface](httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, array $server = array(), [History](../browserkit/history "Symfony\Component\BrowserKit\History") $history = null, [CookieJar](../browserkit/cookiejar "Symfony\Component\BrowserKit\CookieJar") $cookieJar = null) #### Parameters | | | | | --- | --- | --- | | [HttpKernelInterface](httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | $kernel | An HttpKernel instance | | array | $server | The server parameters (equivalent of $\_SERVER) | | [History](../browserkit/history "Symfony\Component\BrowserKit\History") | $history | A History instance to store the browser history | | [CookieJar](../browserkit/cookiejar "Symfony\Component\BrowserKit\CookieJar") | $cookieJar | A CookieJar instance to store the cookies | ### followRedirects(bool $followRedirect = true) Sets whether to automatically follow redirects or not. #### Parameters | | | | | --- | --- | --- | | bool | $followRedirect | Whether to follow redirects | ### bool isFollowingRedirects() Returns whether client automatically follows redirects or not. #### Return Value | | | | --- | --- | | bool | | ### setMaxRedirects(int $maxRedirects) Sets the maximum number of redirects that crawler can follow. #### Parameters | | | | | --- | --- | --- | | int | $maxRedirects | | ### int getMaxRedirects() Returns the maximum number of redirects that crawler can follow. #### Return Value | | | | --- | --- | | int | | ### insulate(bool $insulated = true) Sets the insulated flag. #### Parameters | | | | | --- | --- | --- | | bool | $insulated | Whether to insulate the requests or not | #### Exceptions | | | | --- | --- | | [RuntimeException](http://php.net/RuntimeException) | When Symfony Process Component is not installed | ### setServerParameters(array $server) Sets server parameters. #### Parameters | | | | | --- | --- | --- | | array | $server | An array of server parameters | ### setServerParameter(string $key, string $value) Sets single server parameter. #### Parameters | | | | | --- | --- | --- | | string | $key | A key of the parameter | | string | $value | A value of the parameter | ### string getServerParameter(string $key, string $default = '') Gets single server parameter for specified key. #### Parameters | | | | | --- | --- | --- | | string | $key | A key of the parameter to get | | string | $default | A default value when key is undefined | #### Return Value | | | | --- | --- | | string | A value of the parameter | ### [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") xmlHttpRequest(string $method, string $uri, array $parameters = array(), array $files = array(), array $server = array(), string $content = null, bool $changeHistory = true) #### Parameters | | | | | --- | --- | --- | | string | $method | | | string | $uri | | | array | $parameters | | | array | $files | | | array | $server | | | string | $content | | | bool | $changeHistory | | #### Return Value | | | | --- | --- | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") | | ### [History](../browserkit/history "Symfony\Component\BrowserKit\History") getHistory() Returns the History instance. #### Return Value | | | | --- | --- | | [History](../browserkit/history "Symfony\Component\BrowserKit\History") | A History instance | ### [CookieJar](../browserkit/cookiejar "Symfony\Component\BrowserKit\CookieJar") getCookieJar() Returns the CookieJar instance. #### Return Value | | | | --- | --- | | [CookieJar](../browserkit/cookiejar "Symfony\Component\BrowserKit\CookieJar") | A CookieJar instance | ### [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") getCrawler() Returns the current Crawler instance. #### Return Value | | | | --- | --- | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") | A Crawler instance | ### [Response](../browserkit/response "Symfony\Component\BrowserKit\Response") getInternalResponse() Returns the current BrowserKit Response instance. #### Return Value | | | | --- | --- | | [Response](../browserkit/response "Symfony\Component\BrowserKit\Response") | A BrowserKit Response instance | ### Response getResponse() A Response instance #### Return Value | | | | --- | --- | | Response | | ### [Request](../browserkit/request "Symfony\Component\BrowserKit\Request") getInternalRequest() Returns the current BrowserKit Request instance. #### Return Value | | | | --- | --- | | [Request](../browserkit/request "Symfony\Component\BrowserKit\Request") | A BrowserKit Request instance | ### Request getRequest() A Request instance #### Return Value | | | | --- | --- | | Request | | ### [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") click([Link](../domcrawler/link "Symfony\Component\DomCrawler\Link") $link) Clicks on a given link. #### Parameters | | | | | --- | --- | --- | | [Link](../domcrawler/link "Symfony\Component\DomCrawler\Link") | $link | | #### Return Value | | | | --- | --- | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") | | ### [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") submit([Form](../domcrawler/form "Symfony\Component\DomCrawler\Form") $form, array $values = array()) Submits a form. #### Parameters | | | | | --- | --- | --- | | [Form](../domcrawler/form "Symfony\Component\DomCrawler\Form") | $form | | | array | $values | | #### Return Value | | | | --- | --- | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") | | ### [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") request(string $method, string $uri, array $parameters = array(), array $files = array(), array $server = array(), string $content = null, bool $changeHistory = true) Calls a URI. #### Parameters | | | | | --- | --- | --- | | string | $method | The request method | | string | $uri | The URI to fetch | | array | $parameters | The Request parameters | | array | $files | The files | | array | $server | The server parameters (HTTP headers are referenced with a HTTP\_ prefix as PHP does) | | string | $content | The raw body data | | bool | $changeHistory | Whether to update the history or not (only used internally for back(), forward(), and reload()) | #### Return Value | | | | --- | --- | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") | | ### protected object doRequestInProcess(object $request) Makes a request in another process. #### Parameters | | | | | --- | --- | --- | | object | $request | An origin request instance | #### Return Value | | | | --- | --- | | object | An origin response instance | #### Exceptions | | | | --- | --- | | [RuntimeException](http://php.net/RuntimeException) | When processing returns exit code | ### protected object doRequest(object $request) Makes a request. #### Parameters | | | | | --- | --- | --- | | object | $request | An origin request instance | #### Return Value | | | | --- | --- | | object | An origin response instance | ### protected getScript(object $request) Returns the script to execute when the request must be insulated. #### Parameters | | | | | --- | --- | --- | | object | $request | An origin request instance | ### protected object filterRequest([Request](../browserkit/request "Symfony\Component\BrowserKit\Request") $request) Converts the BrowserKit request to a HttpKernel request. #### Parameters | | | | | --- | --- | --- | | [Request](../browserkit/request "Symfony\Component\BrowserKit\Request") | $request | The BrowserKit Request to filter | #### Return Value | | | | --- | --- | | object | An origin request instance | ### protected [Response](../browserkit/response "Symfony\Component\BrowserKit\Response") filterResponse(object $response) Converts the HttpKernel response to a BrowserKit response. #### Parameters | | | | | --- | --- | --- | | object | $response | The origin response to filter | #### Return Value | | | | --- | --- | | [Response](../browserkit/response "Symfony\Component\BrowserKit\Response") | An BrowserKit Response instance | ### protected [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler")|null createCrawlerFromContent(string $uri, string $content, string $type) Creates a crawler. This method returns null if the DomCrawler component is not available. #### Parameters | | | | | --- | --- | --- | | string | $uri | A URI | | string | $content | Content for the crawler to use | | string | $type | Content type | #### Return Value | | | | --- | --- | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler")|null | | ### [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") back() Goes back in the browser history. #### Return Value | | | | --- | --- | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") | | ### [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") forward() Goes forward in the browser history. #### Return Value | | | | --- | --- | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") | | ### [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") reload() Reloads the current browser. #### Return Value | | | | --- | --- | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") | | ### [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") followRedirect() Follow redirects? #### Return Value | | | | --- | --- | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") | | #### Exceptions | | | | --- | --- | | [LogicException](http://php.net/LogicException) | If request was not a redirect | ### restart() Restarts the client. It flushes history and all cookies. ### protected string getAbsoluteUri(string $uri) Takes a URI and converts it to absolute if it is not already absolute. #### Parameters | | | | | --- | --- | --- | | string | $uri | A URI | #### Return Value | | | | --- | --- | | string | An absolute URI | ### protected [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") requestFromRequest([Request](../browserkit/request "Symfony\Component\BrowserKit\Request") $request, bool $changeHistory = true) Makes a request from a Request object directly. #### Parameters | | | | | --- | --- | --- | | [Request](../browserkit/request "Symfony\Component\BrowserKit\Request") | $request | A Request instance | | bool | $changeHistory | Whether to update the history or not (only used internally for back(), forward(), and reload()) | #### Return Value | | | | --- | --- | | [Crawler](../domcrawler/crawler "Symfony\Component\DomCrawler\Crawler") | | ### catchExceptions(bool $catchExceptions) Sets whether to catch exceptions when the kernel is handling a request. #### Parameters | | | | | --- | --- | --- | | bool | $catchExceptions | Whether to catch exceptions | ### protected getHandleScript() ### protected array filterFiles(array $files) Filters an array of files. This method created test instances of UploadedFile so that the move() method can be called on those instances. If the size of a file is greater than the allowed size (from php.ini) then an invalid UploadedFile is returned with an error set to UPLOAD\_ERR\_INI\_SIZE. #### Parameters | | | | | --- | --- | --- | | array | $files | | #### Return Value | | | | --- | --- | | array | An array with all uploaded files marked as already moved | #### See also | | | | --- | --- | | [UploadedFile](../httpfoundation/file/uploadedfile "Symfony\Component\HttpFoundation\File\UploadedFile") | |
programming_docs
symfony UriSigner UriSigner ========== class **UriSigner** Signs URIs. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $secret, string $parameter = '\_hash') | | | string | [sign](#method_sign)(string $uri) Signs a URI. | | | bool | [check](#method_check)(string $uri) Checks that a URI contains the correct hash. | | Details ------- ### \_\_construct(string $secret, string $parameter = '\_hash') #### Parameters | | | | | --- | --- | --- | | string | $secret | A secret | | string | $parameter | Query string parameter to use | ### string sign(string $uri) Signs a URI. The given URI is signed by adding the query string parameter which value depends on the URI and the secret. #### Parameters | | | | | --- | --- | --- | | string | $uri | A URI to sign | #### Return Value | | | | --- | --- | | string | The signed URI | ### bool check(string $uri) Checks that a URI contains the correct hash. #### Parameters | | | | | --- | --- | --- | | string | $uri | A signed URI | #### Return Value | | | | --- | --- | | bool | True if the URI is signed correctly, false otherwise | symfony Symfony\Component\HttpKernel\Exception Symfony\Component\HttpKernel\Exception ====================================== Classes ------- | | | | --- | --- | | [AccessDeniedHttpException](exception/accessdeniedhttpexception "Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException") | | | [BadRequestHttpException](exception/badrequesthttpexception "Symfony\Component\HttpKernel\Exception\BadRequestHttpException") | | | [ConflictHttpException](exception/conflicthttpexception "Symfony\Component\HttpKernel\Exception\ConflictHttpException") | | | [GoneHttpException](exception/gonehttpexception "Symfony\Component\HttpKernel\Exception\GoneHttpException") | | | [HttpException](exception/httpexception "Symfony\Component\HttpKernel\Exception\HttpException") | HttpException. | | [LengthRequiredHttpException](exception/lengthrequiredhttpexception "Symfony\Component\HttpKernel\Exception\LengthRequiredHttpException") | | | [MethodNotAllowedHttpException](exception/methodnotallowedhttpexception "Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException") | | | [NotAcceptableHttpException](exception/notacceptablehttpexception "Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException") | | | [NotFoundHttpException](exception/notfoundhttpexception "Symfony\Component\HttpKernel\Exception\NotFoundHttpException") | | | [PreconditionFailedHttpException](exception/preconditionfailedhttpexception "Symfony\Component\HttpKernel\Exception\PreconditionFailedHttpException") | | | [PreconditionRequiredHttpException](exception/preconditionrequiredhttpexception "Symfony\Component\HttpKernel\Exception\PreconditionRequiredHttpException") | | | [ServiceUnavailableHttpException](exception/serviceunavailablehttpexception "Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException") | | | [TooManyRequestsHttpException](exception/toomanyrequestshttpexception "Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException") | | | [UnauthorizedHttpException](exception/unauthorizedhttpexception "Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException") | | | [UnprocessableEntityHttpException](exception/unprocessableentityhttpexception "Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException") | | | [UnsupportedMediaTypeHttpException](exception/unsupportedmediatypehttpexception "Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException") | | Interfaces ---------- | | | | --- | --- | | *[HttpExceptionInterface](exception/httpexceptioninterface "Symfony\Component\HttpKernel\Exception\HttpExceptionInterface")* | Interface for HTTP error exceptions. | symfony Symfony\Component\HttpKernel\DataCollector Symfony\Component\HttpKernel\DataCollector ========================================== Classes ------- | | | | --- | --- | | [AjaxDataCollector](datacollector/ajaxdatacollector "Symfony\Component\HttpKernel\DataCollector\AjaxDataCollector") | AjaxDataCollector. | | [ConfigDataCollector](datacollector/configdatacollector "Symfony\Component\HttpKernel\DataCollector\ConfigDataCollector") | | | [DataCollector](datacollector/datacollector "Symfony\Component\HttpKernel\DataCollector\DataCollector") | DataCollector. | | [DumpDataCollector](datacollector/dumpdatacollector "Symfony\Component\HttpKernel\DataCollector\DumpDataCollector") | | | [EventDataCollector](datacollector/eventdatacollector "Symfony\Component\HttpKernel\DataCollector\EventDataCollector") | EventDataCollector. | | [ExceptionDataCollector](datacollector/exceptiondatacollector "Symfony\Component\HttpKernel\DataCollector\ExceptionDataCollector") | ExceptionDataCollector. | | [LoggerDataCollector](datacollector/loggerdatacollector "Symfony\Component\HttpKernel\DataCollector\LoggerDataCollector") | LogDataCollector. | | [MemoryDataCollector](datacollector/memorydatacollector "Symfony\Component\HttpKernel\DataCollector\MemoryDataCollector") | MemoryDataCollector. | | [RequestDataCollector](datacollector/requestdatacollector "Symfony\Component\HttpKernel\DataCollector\RequestDataCollector") | | | [RouterDataCollector](datacollector/routerdatacollector "Symfony\Component\HttpKernel\DataCollector\RouterDataCollector") | RouterDataCollector. | | [TimeDataCollector](datacollector/timedatacollector "Symfony\Component\HttpKernel\DataCollector\TimeDataCollector") | TimeDataCollector. | Interfaces ---------- | | | | --- | --- | | *[DataCollectorInterface](datacollector/datacollectorinterface "Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface")* | DataCollectorInterface. | | *[LateDataCollectorInterface](datacollector/latedatacollectorinterface "Symfony\Component\HttpKernel\DataCollector\LateDataCollectorInterface")* | LateDataCollectorInterface. | symfony KernelInterface KernelInterface ================ interface **KernelInterface** implements [HttpKernelInterface](httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface"), [Serializable](http://php.net/Serializable) The Kernel is the heart of the Symfony system. It manages an environment made of application kernel and bundles. Methods ------- | | | | | --- | --- | --- | | [Response](../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [handle](#method_handle)([Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int $type = self::MASTER\_REQUEST, bool $catch = true) Handles a Request to convert it to a Response. | from [HttpKernelInterface](httpkernelinterface#method_handle "Symfony\Component\HttpKernel\HttpKernelInterface") | | iterable|[BundleInterface](bundle/bundleinterface "Symfony\Component\HttpKernel\Bundle\BundleInterface")[] | [registerBundles](#method_registerBundles)() Returns an array of bundles to register. | | | | [registerContainerConfiguration](#method_registerContainerConfiguration)([LoaderInterface](../config/loader/loaderinterface "Symfony\Component\Config\Loader\LoaderInterface") $loader) Loads the container configuration. | | | | [boot](#method_boot)() Boots the current kernel. | | | | [shutdown](#method_shutdown)() Shutdowns the kernel. | | | [BundleInterface](bundle/bundleinterface "Symfony\Component\HttpKernel\Bundle\BundleInterface")[] | [getBundles](#method_getBundles)() Gets the registered bundle instances. | | | [BundleInterface](bundle/bundleinterface "Symfony\Component\HttpKernel\Bundle\BundleInterface") | [getBundle](#method_getBundle)(string $name) Returns a bundle. | | | string|array | [locateResource](#method_locateResource)(string $name, string $dir = null, bool $first = true) Returns the file path for a given bundle resource. | | | string | [getName](#method_getName)() Gets the name of the kernel. | | | string | [getEnvironment](#method_getEnvironment)() Gets the environment. | | | bool | [isDebug](#method_isDebug)() Checks if debug mode is enabled. | | | string | [getRootDir](#method_getRootDir)() Gets the application root dir (path of the project's Kernel class). | | | [ContainerInterface](../dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface")|null | [getContainer](#method_getContainer)() Gets the current container. | | | int | [getStartTime](#method_getStartTime)() Gets the request start time (not available if debug is disabled). | | | string | [getCacheDir](#method_getCacheDir)() Gets the cache directory. | | | string | [getLogDir](#method_getLogDir)() Gets the log directory. | | | string | [getCharset](#method_getCharset)() Gets the charset of the application. | | Details ------- ### [Response](../httpfoundation/response "Symfony\Component\HttpFoundation\Response") handle([Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int $type = self::MASTER\_REQUEST, bool $catch = true) Handles a Request to convert it to a Response. When $catch is true, the implementation must catch all exceptions and do its best to convert them to a Response instance. #### Parameters | | | | | --- | --- | --- | | [Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | int | $type | The type of the request (one of HttpKernelInterface::MASTER\_REQUEST or HttpKernelInterface::SUB\_REQUEST) | | bool | $catch | Whether to catch exceptions or not | #### Return Value | | | | --- | --- | | [Response](../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | A Response instance | #### Exceptions | | | | --- | --- | | [Exception](http://php.net/Exception) | When an Exception occurs during processing | ### iterable|[BundleInterface](bundle/bundleinterface "Symfony\Component\HttpKernel\Bundle\BundleInterface")[] registerBundles() Returns an array of bundles to register. #### Return Value | | | | --- | --- | | iterable|[BundleInterface](bundle/bundleinterface "Symfony\Component\HttpKernel\Bundle\BundleInterface")[] | An iterable of bundle instances | ### registerContainerConfiguration([LoaderInterface](../config/loader/loaderinterface "Symfony\Component\Config\Loader\LoaderInterface") $loader) Loads the container configuration. #### Parameters | | | | | --- | --- | --- | | [LoaderInterface](../config/loader/loaderinterface "Symfony\Component\Config\Loader\LoaderInterface") | $loader | | ### boot() Boots the current kernel. ### shutdown() Shutdowns the kernel. This method is mainly useful when doing functional testing. ### [BundleInterface](bundle/bundleinterface "Symfony\Component\HttpKernel\Bundle\BundleInterface")[] getBundles() Gets the registered bundle instances. #### Return Value | | | | --- | --- | | [BundleInterface](bundle/bundleinterface "Symfony\Component\HttpKernel\Bundle\BundleInterface")[] | An array of registered bundle instances | ### [BundleInterface](bundle/bundleinterface "Symfony\Component\HttpKernel\Bundle\BundleInterface") getBundle(string $name) Returns a bundle. #### Parameters | | | | | --- | --- | --- | | string | $name | Bundle name | #### Return Value | | | | --- | --- | | [BundleInterface](bundle/bundleinterface "Symfony\Component\HttpKernel\Bundle\BundleInterface") | A BundleInterface instance | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](http://php.net/InvalidArgumentException) | when the bundle is not enabled | ### string|array locateResource(string $name, string $dir = null, bool $first = true) Returns the file path for a given bundle resource. A Resource can be a file or a directory. The resource name must follow the following pattern: ``` "@BundleName/path/to/a/file.something" ``` where BundleName is the name of the bundle and the remaining part is the relative path in the bundle. If $dir is passed, and the first segment of the path is "Resources", this method will look for a file named: ``` $dir/<BundleName>/path/without/Resources ``` before looking in the bundle resource folder. #### Parameters | | | | | --- | --- | --- | | string | $name | A resource name to locate | | string | $dir | A directory where to look for the resource first | | bool | $first | Whether to return the first path or paths for all matching bundles | #### Return Value | | | | --- | --- | | string|array | The absolute path of the resource or an array if $first is false | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](http://php.net/InvalidArgumentException) | if the file cannot be found or the name is not valid | | [RuntimeException](http://php.net/RuntimeException) | if the name contains invalid/unsafe characters | ### string getName() Gets the name of the kernel. #### Return Value | | | | --- | --- | | string | The kernel name | ### string getEnvironment() Gets the environment. #### Return Value | | | | --- | --- | | string | The current environment | ### bool isDebug() Checks if debug mode is enabled. #### Return Value | | | | --- | --- | | bool | true if debug mode is enabled, false otherwise | ### string getRootDir() Gets the application root dir (path of the project's Kernel class). #### Return Value | | | | --- | --- | | string | The Kernel root dir | ### [ContainerInterface](../dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface")|null getContainer() Gets the current container. #### Return Value | | | | --- | --- | | [ContainerInterface](../dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface")|null | A ContainerInterface instance or null when the Kernel is shutdown | ### int getStartTime() Gets the request start time (not available if debug is disabled). #### Return Value | | | | --- | --- | | int | The request start timestamp | ### string getCacheDir() Gets the cache directory. #### Return Value | | | | --- | --- | | string | The cache directory | ### string getLogDir() Gets the log directory. #### Return Value | | | | --- | --- | | string | The log directory | ### string getCharset() Gets the charset of the application. #### Return Value | | | | --- | --- | | string | The charset | symfony KernelEvents KernelEvents ============= class **KernelEvents** Contains all events thrown in the HttpKernel component. Constants --------- | | | | --- | --- | | REQUEST | *The REQUEST event occurs at the very beginning of request dispatching.* This event allows you to create a response for a request before any other code in the framework is executed. | | EXCEPTION | *The EXCEPTION event occurs when an uncaught exception appears.* This event allows you to create a response for a thrown exception or to modify the thrown exception. | | VIEW | *The VIEW event occurs when the return value of a controller is not a Response instance.* This event allows you to create a response for the return value of the controller. | | CONTROLLER | *The CONTROLLER event occurs once a controller was found for handling a request.* This event allows you to change the controller that will handle the request. | | CONTROLLER\_ARGUMENTS | *The CONTROLLER\_ARGUMENTS event occurs once controller arguments have been resolved.* This event allows you to change the arguments that will be passed to the controller. | | RESPONSE | *The RESPONSE event occurs once a response was created for replying to a request.* This event allows you to modify or replace the response that will be replied. | | TERMINATE | *The TERMINATE event occurs once a response was sent.* This event allows you to run expensive post-response jobs. | | FINISH\_REQUEST | *The FINISH\_REQUEST event occurs when a response was generated for a request.* This event allows you to reset the global and environmental state of the application, when it was changed during the request. | symfony Symfony\Component\HttpKernel\Bundle Symfony\Component\HttpKernel\Bundle =================================== Classes ------- | | | | --- | --- | | [Bundle](bundle/bundle "Symfony\Component\HttpKernel\Bundle\Bundle") | An implementation of BundleInterface that adds a few conventions for DependencyInjection extensions and Console commands. | Interfaces ---------- | | | | --- | --- | | *[BundleInterface](bundle/bundleinterface "Symfony\Component\HttpKernel\Bundle\BundleInterface")* | BundleInterface. | symfony Symfony\Component\HttpKernel\Event Symfony\Component\HttpKernel\Event ================================== Classes ------- | | | | --- | --- | | [FilterControllerArgumentsEvent](event/filtercontrollerargumentsevent "Symfony\Component\HttpKernel\Event\FilterControllerArgumentsEvent") | Allows filtering of controller arguments. | | [FilterControllerEvent](event/filtercontrollerevent "Symfony\Component\HttpKernel\Event\FilterControllerEvent") | Allows filtering of a controller callable. | | [FilterResponseEvent](event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") | Allows to filter a Response object. | | [FinishRequestEvent](event/finishrequestevent "Symfony\Component\HttpKernel\Event\FinishRequestEvent") | Triggered whenever a request is fully processed. | | [GetResponseEvent](event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") | Allows to create a response for a request. | | [GetResponseForControllerResultEvent](event/getresponseforcontrollerresultevent "Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent") | Allows to create a response for the return value of a controller. | | [GetResponseForExceptionEvent](event/getresponseforexceptionevent "Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent") | Allows to create a response for a thrown exception. | | [KernelEvent](event/kernelevent "Symfony\Component\HttpKernel\Event\KernelEvent") | Base class for events thrown in the HttpKernel component. | | [PostResponseEvent](event/postresponseevent "Symfony\Component\HttpKernel\Event\PostResponseEvent") | Allows to execute logic after a response was sent. | symfony Symfony\Component\HttpKernel\Fragment Symfony\Component\HttpKernel\Fragment ===================================== Classes ------- | | | | --- | --- | | [AbstractSurrogateFragmentRenderer](fragment/abstractsurrogatefragmentrenderer "Symfony\Component\HttpKernel\Fragment\AbstractSurrogateFragmentRenderer") | Implements Surrogate rendering strategy. | | [EsiFragmentRenderer](fragment/esifragmentrenderer "Symfony\Component\HttpKernel\Fragment\EsiFragmentRenderer") | Implements the ESI rendering strategy. | | [FragmentHandler](fragment/fragmenthandler "Symfony\Component\HttpKernel\Fragment\FragmentHandler") | Renders a URI that represents a resource fragment. | | [HIncludeFragmentRenderer](fragment/hincludefragmentrenderer "Symfony\Component\HttpKernel\Fragment\HIncludeFragmentRenderer") | Implements the Hinclude rendering strategy. | | [InlineFragmentRenderer](fragment/inlinefragmentrenderer "Symfony\Component\HttpKernel\Fragment\InlineFragmentRenderer") | Implements the inline rendering strategy where the Request is rendered by the current HTTP kernel. | | [RoutableFragmentRenderer](fragment/routablefragmentrenderer "Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer") | Adds the possibility to generate a fragment URI for a given Controller. | | [SsiFragmentRenderer](fragment/ssifragmentrenderer "Symfony\Component\HttpKernel\Fragment\SsiFragmentRenderer") | Implements the SSI rendering strategy. | Interfaces ---------- | | | | --- | --- | | *[FragmentRendererInterface](fragment/fragmentrendererinterface "Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface")* | Interface implemented by all rendering strategies. |
programming_docs
symfony Symfony\Component\HttpKernel\Controller Symfony\Component\HttpKernel\Controller ======================================= Namespaces ---------- [Symfony\Component\HttpKernel\Controller\ArgumentResolver](controller/argumentresolver) Classes ------- | | | | --- | --- | | [ArgumentResolver](controller/argumentresolver "Symfony\Component\HttpKernel\Controller\ArgumentResolver") | Responsible for resolving the arguments passed to an action. | | [ContainerControllerResolver](controller/containercontrollerresolver "Symfony\Component\HttpKernel\Controller\ContainerControllerResolver") | A controller resolver searching for a controller in a psr-11 container when using the "service:method" notation. | | [ControllerReference](controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") | Acts as a marker and a data holder for a Controller. | | [ControllerResolver](controller/controllerresolver "Symfony\Component\HttpKernel\Controller\ControllerResolver") | This implementation uses the '\_controller' request attribute to determine the controller to execute. | | [TraceableArgumentResolver](controller/traceableargumentresolver "Symfony\Component\HttpKernel\Controller\TraceableArgumentResolver") | | | [TraceableControllerResolver](controller/traceablecontrollerresolver "Symfony\Component\HttpKernel\Controller\TraceableControllerResolver") | | Interfaces ---------- | | | | --- | --- | | *[ArgumentResolverInterface](controller/argumentresolverinterface "Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface")* | An ArgumentResolverInterface instance knows how to determine the arguments for a specific action. | | *[ArgumentValueResolverInterface](controller/argumentvalueresolverinterface "Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface")* | Responsible for resolving the value of an argument based on its metadata. | | *[ControllerResolverInterface](controller/controllerresolverinterface "Symfony\Component\HttpKernel\Controller\ControllerResolverInterface")* | A ControllerResolverInterface implementation knows how to determine the controller to execute based on a Request object. | symfony TerminableInterface TerminableInterface ==================== interface **TerminableInterface** Terminable extends the Kernel request/response cycle with dispatching a post response event after sending the response and before shutting down the kernel. Methods ------- | | | | | --- | --- | --- | | | [terminate](#method_terminate)([Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Terminates a request/response cycle. | | Details ------- ### terminate([Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Terminates a request/response cycle. Should be called after sending the response and before shutting down the kernel. #### Parameters | | | | | --- | --- | --- | | [Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | symfony HttpKernelInterface HttpKernelInterface ==================== interface **HttpKernelInterface** HttpKernelInterface handles a Request to convert it to a Response. Constants --------- | | | | --- | --- | | MASTER\_REQUEST | | | SUB\_REQUEST | | Methods ------- | | | | | --- | --- | --- | | [Response](../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [handle](#method_handle)([Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int $type = self::MASTER\_REQUEST, bool $catch = true) Handles a Request to convert it to a Response. | | Details ------- ### [Response](../httpfoundation/response "Symfony\Component\HttpFoundation\Response") handle([Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int $type = self::MASTER\_REQUEST, bool $catch = true) Handles a Request to convert it to a Response. When $catch is true, the implementation must catch all exceptions and do its best to convert them to a Response instance. #### Parameters | | | | | --- | --- | --- | | [Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | int | $type | The type of the request (one of HttpKernelInterface::MASTER\_REQUEST or HttpKernelInterface::SUB\_REQUEST) | | bool | $catch | Whether to catch exceptions or not | #### Return Value | | | | --- | --- | | [Response](../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | A Response instance | #### Exceptions | | | | --- | --- | | [Exception](http://php.net/Exception) | When an Exception occurs during processing | symfony Kernel Kernel ======= abstract class **Kernel** implements [KernelInterface](kernelinterface "Symfony\Component\HttpKernel\KernelInterface"), [RebootableInterface](rebootableinterface "Symfony\Component\HttpKernel\RebootableInterface"), [TerminableInterface](terminableinterface "Symfony\Component\HttpKernel\TerminableInterface") The Kernel is the heart of the Symfony system. It manages an environment made of bundles. Constants --------- | | | | --- | --- | | VERSION | | | VERSION\_ID | | | MAJOR\_VERSION | | | MINOR\_VERSION | | | RELEASE\_VERSION | | | EXTRA\_VERSION | | | END\_OF\_MAINTENANCE | | | END\_OF\_LIFE | | Properties ---------- | | | | | | --- | --- | --- | --- | | protected [BundleInterface](bundle/bundleinterface "Symfony\Component\HttpKernel\Bundle\BundleInterface")[] | $bundles | | | | protected | $container | | | | protected | $rootDir | | | | protected | $environment | | | | protected | $debug | | | | protected | $booted | | | | protected | $name | | | | protected | $startTime | | | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $environment, bool $debug) | | | | [\_\_clone](#method___clone)() | | | | [boot](#method_boot)() Boots the current kernel. | | | | [reboot](#method_reboot)(string|null $warmupDir) Reboots a kernel. | | | | [terminate](#method_terminate)([Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Terminates a request/response cycle. | | | | [shutdown](#method_shutdown)() Shutdowns the kernel. | | | [Response](../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [handle](#method_handle)([Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int $type = HttpKernelInterface::MASTER\_REQUEST, bool $catch = true) Handles a Request to convert it to a Response. | | | [HttpKernel](httpkernel "Symfony\Component\HttpKernel\HttpKernel") | [getHttpKernel](#method_getHttpKernel)() Gets a HTTP kernel from the container. | | | [BundleInterface](bundle/bundleinterface "Symfony\Component\HttpKernel\Bundle\BundleInterface")[] | [getBundles](#method_getBundles)() Gets the registered bundle instances. | | | [BundleInterface](bundle/bundleinterface "Symfony\Component\HttpKernel\Bundle\BundleInterface") | [getBundle](#method_getBundle)(string $name) Returns a bundle. | | | string|array | [locateResource](#method_locateResource)(string $name, string $dir = null, bool $first = true) Returns the file path for a given bundle resource. | | | string | [getName](#method_getName)() Gets the name of the kernel. | | | string | [getEnvironment](#method_getEnvironment)() Gets the environment. | | | bool | [isDebug](#method_isDebug)() Checks if debug mode is enabled. | | | string | [getRootDir](#method_getRootDir)() Gets the application root dir (path of the project's Kernel class). | | | string | [getProjectDir](#method_getProjectDir)() Gets the application root dir (path of the project's composer file). | | | [ContainerInterface](../dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface")|null | [getContainer](#method_getContainer)() Gets the current container. | | | | [setAnnotatedClassCache](#method_setAnnotatedClassCache)(array $annotatedClasses) | | | int | [getStartTime](#method_getStartTime)() Gets the request start time (not available if debug is disabled). | | | string | [getCacheDir](#method_getCacheDir)() Gets the cache directory. | | | string | [getLogDir](#method_getLogDir)() Gets the log directory. | | | string | [getCharset](#method_getCharset)() Gets the charset of the application. | | | array | [getAnnotatedClassesToCompile](#method_getAnnotatedClassesToCompile)() Gets the patterns defining the classes to parse and cache for annotations. | | | | [initializeBundles](#method_initializeBundles)() Initializes bundles. | | | | [build](#method_build)([ContainerBuilder](../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) The extension point similar to the Bundle::build() method. | | | string | [getContainerClass](#method_getContainerClass)() Gets the container class. | | | string | [getContainerBaseClass](#method_getContainerBaseClass)() Gets the container's base class. | | | | [initializeContainer](#method_initializeContainer)() Initializes the service container. | | | array | [getKernelParameters](#method_getKernelParameters)() Returns the kernel parameters. | | | [ContainerBuilder](../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | [buildContainer](#method_buildContainer)() Builds the service container. | | | | [prepareContainer](#method_prepareContainer)([ContainerBuilder](../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Prepares the ContainerBuilder before it is compiled. | | | [ContainerBuilder](../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | [getContainerBuilder](#method_getContainerBuilder)() Gets a new ContainerBuilder instance used to build the service container. | | | | [dumpContainer](#method_dumpContainer)([ConfigCache](../config/configcache "Symfony\Component\Config\ConfigCache") $cache, [ContainerBuilder](../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container, string $class, string $baseClass) Dumps the service container to PHP code in the cache. | | | [DelegatingLoader](../config/loader/delegatingloader "Symfony\Component\Config\Loader\DelegatingLoader") | [getContainerLoader](#method_getContainerLoader)([ContainerInterface](../dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface") $container) Returns a loader for the container. | | | static string | [stripComments](#method_stripComments)(string $source) Removes comments from a PHP source string. | | | | [serialize](#method_serialize)() | | | | [unserialize](#method_unserialize)($data) | | Details ------- ### \_\_construct(string $environment, bool $debug) #### Parameters | | | | | --- | --- | --- | | string | $environment | | | bool | $debug | | ### \_\_clone() ### boot() Boots the current kernel. ### reboot(string|null $warmupDir) Reboots a kernel. The getCacheDir() method of a rebootable kernel should not be called while building the container. Use the %kernel.cache\_dir% parameter instead. #### Parameters | | | | | --- | --- | --- | | string|null | $warmupDir | pass null to reboot in the regular cache directory | ### terminate([Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Terminates a request/response cycle. Should be called after sending the response and before shutting down the kernel. #### Parameters | | | | | --- | --- | --- | | [Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | ### shutdown() Shutdowns the kernel. This method is mainly useful when doing functional testing. ### [Response](../httpfoundation/response "Symfony\Component\HttpFoundation\Response") handle([Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int $type = HttpKernelInterface::MASTER\_REQUEST, bool $catch = true) Handles a Request to convert it to a Response. When $catch is true, the implementation must catch all exceptions and do its best to convert them to a Response instance. #### Parameters | | | | | --- | --- | --- | | [Request](../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | int | $type | The type of the request (one of HttpKernelInterface::MASTER\_REQUEST or HttpKernelInterface::SUB\_REQUEST) | | bool | $catch | Whether to catch exceptions or not | #### Return Value | | | | --- | --- | | [Response](../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | A Response instance | #### Exceptions | | | | --- | --- | | [Exception](http://php.net/Exception) | When an Exception occurs during processing | ### protected [HttpKernel](httpkernel "Symfony\Component\HttpKernel\HttpKernel") getHttpKernel() Gets a HTTP kernel from the container. #### Return Value | | | | --- | --- | | [HttpKernel](httpkernel "Symfony\Component\HttpKernel\HttpKernel") | | ### [BundleInterface](bundle/bundleinterface "Symfony\Component\HttpKernel\Bundle\BundleInterface")[] getBundles() Gets the registered bundle instances. #### Return Value | | | | --- | --- | | [BundleInterface](bundle/bundleinterface "Symfony\Component\HttpKernel\Bundle\BundleInterface")[] | An array of registered bundle instances | ### [BundleInterface](bundle/bundleinterface "Symfony\Component\HttpKernel\Bundle\BundleInterface") getBundle(string $name) Returns a bundle. #### Parameters | | | | | --- | --- | --- | | string | $name | Bundle name | #### Return Value | | | | --- | --- | | [BundleInterface](bundle/bundleinterface "Symfony\Component\HttpKernel\Bundle\BundleInterface") | A BundleInterface instance | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](http://php.net/InvalidArgumentException) | when the bundle is not enabled | ### string|array locateResource(string $name, string $dir = null, bool $first = true) Returns the file path for a given bundle resource. A Resource can be a file or a directory. The resource name must follow the following pattern: ``` "@BundleName/path/to/a/file.something" ``` where BundleName is the name of the bundle and the remaining part is the relative path in the bundle. If $dir is passed, and the first segment of the path is "Resources", this method will look for a file named: ``` $dir/<BundleName>/path/without/Resources ``` before looking in the bundle resource folder. #### Parameters | | | | | --- | --- | --- | | string | $name | A resource name to locate | | string | $dir | A directory where to look for the resource first | | bool | $first | Whether to return the first path or paths for all matching bundles | #### Return Value | | | | --- | --- | | string|array | The absolute path of the resource or an array if $first is false | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](http://php.net/InvalidArgumentException) | if the file cannot be found or the name is not valid | | [RuntimeException](http://php.net/RuntimeException) | if the name contains invalid/unsafe characters | ### string getName() Gets the name of the kernel. #### Return Value | | | | --- | --- | | string | The kernel name | ### string getEnvironment() Gets the environment. #### Return Value | | | | --- | --- | | string | The current environment | ### bool isDebug() Checks if debug mode is enabled. #### Return Value | | | | --- | --- | | bool | true if debug mode is enabled, false otherwise | ### string getRootDir() Gets the application root dir (path of the project's Kernel class). #### Return Value | | | | --- | --- | | string | The Kernel root dir | ### string getProjectDir() Gets the application root dir (path of the project's composer file). #### Return Value | | | | --- | --- | | string | The project root dir | ### [ContainerInterface](../dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface")|null getContainer() Gets the current container. #### Return Value | | | | --- | --- | | [ContainerInterface](../dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface")|null | A ContainerInterface instance or null when the Kernel is shutdown | ### setAnnotatedClassCache(array $annotatedClasses) #### Parameters | | | | | --- | --- | --- | | array | $annotatedClasses | | ### int getStartTime() Gets the request start time (not available if debug is disabled). #### Return Value | | | | --- | --- | | int | The request start timestamp | ### string getCacheDir() Gets the cache directory. #### Return Value | | | | --- | --- | | string | The cache directory | ### string getLogDir() Gets the log directory. #### Return Value | | | | --- | --- | | string | The log directory | ### string getCharset() Gets the charset of the application. #### Return Value | | | | --- | --- | | string | The charset | ### array getAnnotatedClassesToCompile() Gets the patterns defining the classes to parse and cache for annotations. #### Return Value | | | | --- | --- | | array | | ### protected initializeBundles() Initializes bundles. #### Exceptions | | | | --- | --- | | [LogicException](http://php.net/LogicException) | if two bundles share a common name | ### protected build([ContainerBuilder](../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) The extension point similar to the Bundle::build() method. Use this method to register compiler passes and manipulate the container during the building process. #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | ### protected string getContainerClass() Gets the container class. #### Return Value | | | | --- | --- | | string | The container class | ### protected string getContainerBaseClass() Gets the container's base class. All names except Container must be fully qualified. #### Return Value | | | | --- | --- | | string | | ### protected initializeContainer() Initializes the service container. The cached version of the service container is used when fresh, otherwise the container is built. ### protected array getKernelParameters() Returns the kernel parameters. #### Return Value | | | | --- | --- | | array | An array of kernel parameters | ### protected [ContainerBuilder](../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") buildContainer() Builds the service container. #### Return Value | | | | --- | --- | | [ContainerBuilder](../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | The compiled service container | #### Exceptions | | | | --- | --- | | [RuntimeException](http://php.net/RuntimeException) | | ### protected prepareContainer([ContainerBuilder](../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Prepares the ContainerBuilder before it is compiled. #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | ### protected [ContainerBuilder](../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") getContainerBuilder() Gets a new ContainerBuilder instance used to build the service container. #### Return Value | | | | --- | --- | | [ContainerBuilder](../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | | ### protected dumpContainer([ConfigCache](../config/configcache "Symfony\Component\Config\ConfigCache") $cache, [ContainerBuilder](../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container, string $class, string $baseClass) Dumps the service container to PHP code in the cache. #### Parameters | | | | | --- | --- | --- | | [ConfigCache](../config/configcache "Symfony\Component\Config\ConfigCache") | $cache | The config cache | | [ContainerBuilder](../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | The service container | | string | $class | The name of the class to generate | | string | $baseClass | The name of the container's base class | ### protected [DelegatingLoader](../config/loader/delegatingloader "Symfony\Component\Config\Loader\DelegatingLoader") getContainerLoader([ContainerInterface](../dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface") $container) Returns a loader for the container. #### Parameters | | | | | --- | --- | --- | | [ContainerInterface](../dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface") | $container | | #### Return Value | | | | --- | --- | | [DelegatingLoader](../config/loader/delegatingloader "Symfony\Component\Config\Loader\DelegatingLoader") | The loader | ### static string stripComments(string $source) Removes comments from a PHP source string. We don't use the PHP php\_strip\_whitespace() function as we want the content to be readable and well-formatted. #### Parameters | | | | | --- | --- | --- | | string | $source | A PHP string | #### Return Value | | | | --- | --- | | string | The PHP string with the comments removed | ### serialize() ### unserialize($data) #### Parameters | | | | | --- | --- | --- | | | $data | |
programming_docs
symfony Symfony\Component\HttpKernel\Log Symfony\Component\HttpKernel\Log ================================ Classes ------- | | | | --- | --- | | [Logger](log/logger "Symfony\Component\HttpKernel\Log\Logger") | Minimalist PSR-3 logger designed to write in stderr or any other stream. | Interfaces ---------- | | | | --- | --- | | *[DebugLoggerInterface](log/debugloggerinterface "Symfony\Component\HttpKernel\Log\DebugLoggerInterface")* | DebugLoggerInterface. | symfony Symfony\Component\HttpKernel\Profiler Symfony\Component\HttpKernel\Profiler ===================================== Classes ------- | | | | --- | --- | | [FileProfilerStorage](profiler/fileprofilerstorage "Symfony\Component\HttpKernel\Profiler\FileProfilerStorage") | Storage for profiler using files. | | [Profile](profiler/profile "Symfony\Component\HttpKernel\Profiler\Profile") | Profile. | | [Profiler](profiler/profiler "Symfony\Component\HttpKernel\Profiler\Profiler") | Profiler. | Interfaces ---------- | | | | --- | --- | | *[ProfilerStorageInterface](profiler/profilerstorageinterface "Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface")* | ProfilerStorageInterface. | symfony Symfony\Component\HttpKernel\DependencyInjection Symfony\Component\HttpKernel\DependencyInjection ================================================ Classes ------- | | | | --- | --- | | [AddAnnotatedClassesToCachePass](dependencyinjection/addannotatedclassestocachepass "Symfony\Component\HttpKernel\DependencyInjection\AddAnnotatedClassesToCachePass") | Sets the classes to compile in the cache for the container. | | [ConfigurableExtension](dependencyinjection/configurableextension "Symfony\Component\HttpKernel\DependencyInjection\ConfigurableExtension") | This extension sub-class provides first-class integration with the Config/Definition Component. | | [ControllerArgumentValueResolverPass](dependencyinjection/controllerargumentvalueresolverpass "Symfony\Component\HttpKernel\DependencyInjection\ControllerArgumentValueResolverPass") | Gathers and configures the argument value resolvers. | | [Extension](dependencyinjection/extension "Symfony\Component\HttpKernel\DependencyInjection\Extension") | Allow adding classes to the class cache. | | [FragmentRendererPass](dependencyinjection/fragmentrendererpass "Symfony\Component\HttpKernel\DependencyInjection\FragmentRendererPass") | Adds services tagged kernel.fragment\_renderer as HTTP content rendering strategies. | | [LazyLoadingFragmentHandler](dependencyinjection/lazyloadingfragmenthandler "Symfony\Component\HttpKernel\DependencyInjection\LazyLoadingFragmentHandler") | Lazily loads fragment renderers from the dependency injection container. | | [LoggerPass](dependencyinjection/loggerpass "Symfony\Component\HttpKernel\DependencyInjection\LoggerPass") | Registers the default logger if necessary. | | [MergeExtensionConfigurationPass](dependencyinjection/mergeextensionconfigurationpass "Symfony\Component\HttpKernel\DependencyInjection\MergeExtensionConfigurationPass") | Ensures certain extensions are always loaded. | | [RegisterControllerArgumentLocatorsPass](dependencyinjection/registercontrollerargumentlocatorspass "Symfony\Component\HttpKernel\DependencyInjection\RegisterControllerArgumentLocatorsPass") | Creates the service-locators required by ServiceValueResolver. | | [RemoveEmptyControllerArgumentLocatorsPass](dependencyinjection/removeemptycontrollerargumentlocatorspass "Symfony\Component\HttpKernel\DependencyInjection\RemoveEmptyControllerArgumentLocatorsPass") | Removes empty service-locators registered for ServiceValueResolver. | | [ResettableServicePass](dependencyinjection/resettableservicepass "Symfony\Component\HttpKernel\DependencyInjection\ResettableServicePass") | | | [ServicesResetter](dependencyinjection/servicesresetter "Symfony\Component\HttpKernel\DependencyInjection\ServicesResetter") | Resets provided services. | symfony Symfony\Component\HttpKernel\Config Symfony\Component\HttpKernel\Config =================================== Classes ------- | | | | --- | --- | | [FileLocator](config/filelocator "Symfony\Component\HttpKernel\Config\FileLocator") | FileLocator uses the KernelInterface to locate resources in bundles. | symfony Symfony\Component\HttpKernel\Debug Symfony\Component\HttpKernel\Debug ================================== Classes ------- | | | | --- | --- | | [FileLinkFormatter](debug/filelinkformatter "Symfony\Component\HttpKernel\Debug\FileLinkFormatter") | Formats debug file links. | | [TraceableEventDispatcher](debug/traceableeventdispatcher "Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher") | Collects some data about event listeners. | symfony Symfony\Component\HttpKernel\EventListener Symfony\Component\HttpKernel\EventListener ========================================== Classes ------- | | | | --- | --- | | [AbstractSessionListener](eventlistener/abstractsessionlistener "Symfony\Component\HttpKernel\EventListener\AbstractSessionListener") | Sets the session onto the request on the "kernel.request" event and saves it on the "kernel.response" event. | | [AbstractTestSessionListener](eventlistener/abstracttestsessionlistener "Symfony\Component\HttpKernel\EventListener\AbstractTestSessionListener") | TestSessionListener. | | [AddRequestFormatsListener](eventlistener/addrequestformatslistener "Symfony\Component\HttpKernel\EventListener\AddRequestFormatsListener") | Adds configured formats to each request. | | [DebugHandlersListener](eventlistener/debughandlerslistener "Symfony\Component\HttpKernel\EventListener\DebugHandlersListener") | Configures errors and exceptions handlers. | | [DumpListener](eventlistener/dumplistener "Symfony\Component\HttpKernel\EventListener\DumpListener") | Configures dump() handler. | | [ExceptionListener](eventlistener/exceptionlistener "Symfony\Component\HttpKernel\EventListener\ExceptionListener") | ExceptionListener. | | [FragmentListener](eventlistener/fragmentlistener "Symfony\Component\HttpKernel\EventListener\FragmentListener") | Handles content fragments represented by special URIs. | | [LocaleListener](eventlistener/localelistener "Symfony\Component\HttpKernel\EventListener\LocaleListener") | Initializes the locale based on the current request. | | [ProfilerListener](eventlistener/profilerlistener "Symfony\Component\HttpKernel\EventListener\ProfilerListener") | ProfilerListener collects data for the current request by listening to the kernel events. | | [ResponseListener](eventlistener/responselistener "Symfony\Component\HttpKernel\EventListener\ResponseListener") | ResponseListener fixes the Response headers based on the Request. | | [RouterListener](eventlistener/routerlistener "Symfony\Component\HttpKernel\EventListener\RouterListener") | Initializes the context from the request and sets request attributes based on a matching route. | | [SaveSessionListener](eventlistener/savesessionlistener "Symfony\Component\HttpKernel\EventListener\SaveSessionListener") deprecated | | | [SessionListener](eventlistener/sessionlistener "Symfony\Component\HttpKernel\EventListener\SessionListener") | Sets the session in the request. | | [StreamedResponseListener](eventlistener/streamedresponselistener "Symfony\Component\HttpKernel\EventListener\StreamedResponseListener") | StreamedResponseListener is responsible for sending the Response to the client. | | [SurrogateListener](eventlistener/surrogatelistener "Symfony\Component\HttpKernel\EventListener\SurrogateListener") | SurrogateListener adds a Surrogate-Control HTTP header when the Response needs to be parsed for Surrogates. | | [TestSessionListener](eventlistener/testsessionlistener "Symfony\Component\HttpKernel\EventListener\TestSessionListener") | Sets the session in the request. | | [TranslatorListener](eventlistener/translatorlistener "Symfony\Component\HttpKernel\EventListener\TranslatorListener") | Synchronizes the locale between the request and the translator. | | [ValidateRequestListener](eventlistener/validaterequestlistener "Symfony\Component\HttpKernel\EventListener\ValidateRequestListener") | Validates Requests. | symfony Symfony\Component\HttpKernel\ControllerMetadata Symfony\Component\HttpKernel\ControllerMetadata =============================================== Classes ------- | | | | --- | --- | | [ArgumentMetadata](controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") | Responsible for storing metadata of an argument. | | [ArgumentMetadataFactory](controllermetadata/argumentmetadatafactory "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadataFactory") | Builds {see ArgumentMetadata} objects based on the given Controller. | Interfaces ---------- | | | | --- | --- | | *[ArgumentMetadataFactoryInterface](controllermetadata/argumentmetadatafactoryinterface "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadataFactoryInterface")* | Builds method argument data. | symfony Symfony\Component\HttpKernel\CacheClearer Symfony\Component\HttpKernel\CacheClearer ========================================= Classes ------- | | | | --- | --- | | [ChainCacheClearer](cacheclearer/chaincacheclearer "Symfony\Component\HttpKernel\CacheClearer\ChainCacheClearer") | ChainCacheClearer. | | [Psr6CacheClearer](cacheclearer/psr6cacheclearer "Symfony\Component\HttpKernel\CacheClearer\Psr6CacheClearer") | | Interfaces ---------- | | | | --- | --- | | *[CacheClearerInterface](cacheclearer/cacheclearerinterface "Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface")* | CacheClearerInterface. | symfony RebootableInterface RebootableInterface ==================== interface **RebootableInterface** Allows the Kernel to be rebooted using a temporary cache directory. Methods ------- | | | | | --- | --- | --- | | | [reboot](#method_reboot)(string|null $warmupDir) Reboots a kernel. | | Details ------- ### reboot(string|null $warmupDir) Reboots a kernel. The getCacheDir() method of a rebootable kernel should not be called while building the container. Use the %kernel.cache\_dir% parameter instead. #### Parameters | | | | | --- | --- | --- | | string|null | $warmupDir | pass null to reboot in the regular cache directory | symfony Symfony\Component\HttpKernel\CacheWarmer Symfony\Component\HttpKernel\CacheWarmer ======================================== Classes ------- | | | | --- | --- | | [CacheWarmer](cachewarmer/cachewarmer "Symfony\Component\HttpKernel\CacheWarmer\CacheWarmer") | Abstract cache warmer that knows how to write a file to the cache. | | [CacheWarmerAggregate](cachewarmer/cachewarmeraggregate "Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerAggregate") | Aggregates several cache warmers into a single one. | Interfaces ---------- | | | | --- | --- | | *[CacheWarmerInterface](cachewarmer/cachewarmerinterface "Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface")* | Interface for classes able to warm up the cache. | | *[WarmableInterface](cachewarmer/warmableinterface "Symfony\Component\HttpKernel\CacheWarmer\WarmableInterface")* | Interface for classes that support warming their cache. | symfony Symfony\Component\HttpKernel\HttpCache Symfony\Component\HttpKernel\HttpCache ====================================== Classes ------- | | | | --- | --- | | [AbstractSurrogate](httpcache/abstractsurrogate "Symfony\Component\HttpKernel\HttpCache\AbstractSurrogate") | Abstract class implementing Surrogate capabilities to Request and Response instances. | | [Esi](httpcache/esi "Symfony\Component\HttpKernel\HttpCache\Esi") | Esi implements the ESI capabilities to Request and Response instances. | | [HttpCache](httpcache/httpcache "Symfony\Component\HttpKernel\HttpCache\HttpCache") | Cache provides HTTP caching. | | [ResponseCacheStrategy](httpcache/responsecachestrategy "Symfony\Component\HttpKernel\HttpCache\ResponseCacheStrategy") | ResponseCacheStrategy knows how to compute the Response cache HTTP header based on the different response cache headers. | | [Ssi](httpcache/ssi "Symfony\Component\HttpKernel\HttpCache\Ssi") | Ssi implements the SSI capabilities to Request and Response instances. | | [Store](httpcache/store "Symfony\Component\HttpKernel\HttpCache\Store") | Store implements all the logic for storing cache metadata (Request and Response headers). | | [SubRequestHandler](httpcache/subrequesthandler "Symfony\Component\HttpKernel\HttpCache\SubRequestHandler") | | Interfaces ---------- | | | | --- | --- | | *[ResponseCacheStrategyInterface](httpcache/responsecachestrategyinterface "Symfony\Component\HttpKernel\HttpCache\ResponseCacheStrategyInterface")* | ResponseCacheStrategyInterface implementations know how to compute the Response cache HTTP header based on the different response cache headers. | | *[StoreInterface](httpcache/storeinterface "Symfony\Component\HttpKernel\HttpCache\StoreInterface")* | Interface implemented by HTTP cache stores. | | *[SurrogateInterface](httpcache/surrogateinterface "Symfony\Component\HttpKernel\HttpCache\SurrogateInterface")* | | symfony EventDataCollector EventDataCollector =================== class **EventDataCollector** extends [DataCollector](datacollector "Symfony\Component\HttpKernel\DataCollector\DataCollector") implements [LateDataCollectorInterface](latedatacollectorinterface "Symfony\Component\HttpKernel\DataCollector\LateDataCollectorInterface") EventDataCollector. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $data | | from [DataCollector](datacollector#property_data "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | protected | $dispatcher | | | Methods ------- | | | | | --- | --- | --- | | | [serialize](#method_serialize)() | from [DataCollector](datacollector#method_serialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [unserialize](#method_unserialize)($data) | from [DataCollector](datacollector#method_unserialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | [cloneVar](#method_cloneVar)(mixed $var) Converts the variable into a serializable Data instance. | from [DataCollector](datacollector#method_cloneVar "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | callable[] | [getCasters](#method_getCasters)() | from [DataCollector](datacollector#method_getCasters "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [\_\_construct](#method___construct)([EventDispatcherInterface](../../eventdispatcher/eventdispatcherinterface "Symfony\Component\EventDispatcher\EventDispatcherInterface") $dispatcher = null) | | | | [collect](#method_collect)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. | | | | [reset](#method_reset)() Resets this data collector to its initial state. | | | | [lateCollect](#method_lateCollect)() Collects data as late as possible. | | | | [setCalledListeners](#method_setCalledListeners)(array $listeners) Sets the called listeners. | | | array | [getCalledListeners](#method_getCalledListeners)() Gets the called listeners. | | | | [setNotCalledListeners](#method_setNotCalledListeners)(array $listeners) Sets the not called listeners. | | | array | [getNotCalledListeners](#method_getNotCalledListeners)() Gets the not called listeners. | | | | [setOrphanedEvents](#method_setOrphanedEvents)(array $events) Sets the orphaned events. | | | array | [getOrphanedEvents](#method_getOrphanedEvents)() Gets the orphaned events. | | | string | [getName](#method_getName)() Returns the name of the collector. | | Details ------- ### serialize() ### unserialize($data) #### Parameters | | | | | --- | --- | --- | | | $data | | ### protected [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") cloneVar(mixed $var) Converts the variable into a serializable Data instance. This array can be displayed in the template using the VarDumper component. #### Parameters | | | | | --- | --- | --- | | mixed | $var | | #### Return Value | | | | --- | --- | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | | ### protected callable[] getCasters() #### Return Value | | | | --- | --- | | callable[] | The casters to add to the cloner | ### \_\_construct([EventDispatcherInterface](../../eventdispatcher/eventdispatcherinterface "Symfony\Component\EventDispatcher\EventDispatcherInterface") $dispatcher = null) #### Parameters | | | | | --- | --- | --- | | [EventDispatcherInterface](../../eventdispatcher/eventdispatcherinterface "Symfony\Component\EventDispatcher\EventDispatcherInterface") | $dispatcher | | ### collect([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | | [Exception](http://php.net/Exception) | $exception | | ### reset() Resets this data collector to its initial state. ### lateCollect() Collects data as late as possible. ### setCalledListeners(array $listeners) Sets the called listeners. #### Parameters | | | | | --- | --- | --- | | array | $listeners | An array of called listeners | #### See also | | | | --- | --- | | [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | | ### array getCalledListeners() Gets the called listeners. #### Return Value | | | | --- | --- | | array | An array of called listeners | #### See also | | | | --- | --- | | [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | | ### setNotCalledListeners(array $listeners) Sets the not called listeners. #### Parameters | | | | | --- | --- | --- | | array | $listeners | | #### See also | | | | --- | --- | | [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | | ### array getNotCalledListeners() Gets the not called listeners. #### Return Value | | | | --- | --- | | array | | #### See also | | | | --- | --- | | [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | | ### setOrphanedEvents(array $events) Sets the orphaned events. #### Parameters | | | | | --- | --- | --- | | array | $events | An array of orphaned events | #### See also | | | | --- | --- | | [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | | ### array getOrphanedEvents() Gets the orphaned events. #### Return Value | | | | --- | --- | | array | An array of orphaned events | #### See also | | | | --- | --- | | [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | | ### string getName() Returns the name of the collector. #### Return Value | | | | --- | --- | | string | The collector name |
programming_docs
symfony ConfigDataCollector ConfigDataCollector ==================== class **ConfigDataCollector** extends [DataCollector](datacollector "Symfony\Component\HttpKernel\DataCollector\DataCollector") implements [LateDataCollectorInterface](latedatacollectorinterface "Symfony\Component\HttpKernel\DataCollector\LateDataCollectorInterface") Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $data | | from [DataCollector](datacollector#property_data "Symfony\Component\HttpKernel\DataCollector\DataCollector") | Methods ------- | | | | | --- | --- | --- | | | [serialize](#method_serialize)() | from [DataCollector](datacollector#method_serialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [unserialize](#method_unserialize)($data) | from [DataCollector](datacollector#method_unserialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | [cloneVar](#method_cloneVar)(mixed $var) Converts the variable into a serializable Data instance. | from [DataCollector](datacollector#method_cloneVar "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | callable[] | [getCasters](#method_getCasters)() | from [DataCollector](datacollector#method_getCasters "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [\_\_construct](#method___construct)(string $name = null, string $version = null) | | | | [setKernel](#method_setKernel)([KernelInterface](../kernelinterface "Symfony\Component\HttpKernel\KernelInterface") $kernel = null) Sets the Kernel associated with this Request. | | | | [collect](#method_collect)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. | | | | [reset](#method_reset)() Resets this data collector to its initial state. | | | | [lateCollect](#method_lateCollect)() Collects data as late as possible. | | | | [getApplicationName](#method_getApplicationName)() | | | | [getApplicationVersion](#method_getApplicationVersion)() | | | string | [getToken](#method_getToken)() Gets the token. | | | string | [getSymfonyVersion](#method_getSymfonyVersion)() Gets the Symfony version. | | | string | [getSymfonyState](#method_getSymfonyState)() Returns the state of the current Symfony release. | | | string | [getSymfonyMinorVersion](#method_getSymfonyMinorVersion)() Returns the minor Symfony version used (without patch numbers of extra suffix like "RC", "beta", etc.). | | | string | [getSymfonyEom](#method_getSymfonyEom)() Returns the human redable date when this Symfony version ends its maintenance period. | | | string | [getSymfonyEol](#method_getSymfonyEol)() Returns the human redable date when this Symfony version reaches its "end of life" and won't receive bugs or security fixes. | | | string | [getPhpVersion](#method_getPhpVersion)() Gets the PHP version. | | | string|null | [getPhpVersionExtra](#method_getPhpVersionExtra)() Gets the PHP version extra part. | | | int | [getPhpArchitecture](#method_getPhpArchitecture)() | | | string | [getPhpIntlLocale](#method_getPhpIntlLocale)() | | | string | [getPhpTimezone](#method_getPhpTimezone)() | | | string | [getAppName](#method_getAppName)() Gets the application name. | | | string | [getEnv](#method_getEnv)() Gets the environment. | | | bool | [isDebug](#method_isDebug)() Returns true if the debug is enabled. | | | bool | [hasXDebug](#method_hasXDebug)() Returns true if the XDebug is enabled. | | | bool | [hasApcu](#method_hasApcu)() Returns true if APCu is enabled. | | | bool | [hasZendOpcache](#method_hasZendOpcache)() Returns true if Zend OPcache is enabled. | | | | [getBundles](#method_getBundles)() | | | string | [getSapiName](#method_getSapiName)() Gets the PHP SAPI name. | | | string | [getName](#method_getName)() Returns the name of the collector. | | Details ------- ### serialize() ### unserialize($data) #### Parameters | | | | | --- | --- | --- | | | $data | | ### protected [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") cloneVar(mixed $var) Converts the variable into a serializable Data instance. This array can be displayed in the template using the VarDumper component. #### Parameters | | | | | --- | --- | --- | | mixed | $var | | #### Return Value | | | | --- | --- | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | | ### protected callable[] getCasters() #### Return Value | | | | --- | --- | | callable[] | The casters to add to the cloner | ### \_\_construct(string $name = null, string $version = null) #### Parameters | | | | | --- | --- | --- | | string | $name | The name of the application using the web profiler | | string | $version | The version of the application using the web profiler | ### setKernel([KernelInterface](../kernelinterface "Symfony\Component\HttpKernel\KernelInterface") $kernel = null) Sets the Kernel associated with this Request. #### Parameters | | | | | --- | --- | --- | | [KernelInterface](../kernelinterface "Symfony\Component\HttpKernel\KernelInterface") | $kernel | | ### collect([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | | [Exception](http://php.net/Exception) | $exception | | ### reset() Resets this data collector to its initial state. ### lateCollect() Collects data as late as possible. ### getApplicationName() ### getApplicationVersion() ### string getToken() Gets the token. #### Return Value | | | | --- | --- | | string | The token | ### string getSymfonyVersion() Gets the Symfony version. #### Return Value | | | | --- | --- | | string | The Symfony version | ### string getSymfonyState() Returns the state of the current Symfony release. #### Return Value | | | | --- | --- | | string | One of: unknown, dev, stable, eom, eol | ### string getSymfonyMinorVersion() Returns the minor Symfony version used (without patch numbers of extra suffix like "RC", "beta", etc.). #### Return Value | | | | --- | --- | | string | | ### string getSymfonyEom() Returns the human redable date when this Symfony version ends its maintenance period. #### Return Value | | | | --- | --- | | string | | ### string getSymfonyEol() Returns the human redable date when this Symfony version reaches its "end of life" and won't receive bugs or security fixes. #### Return Value | | | | --- | --- | | string | | ### string getPhpVersion() Gets the PHP version. #### Return Value | | | | --- | --- | | string | The PHP version | ### string|null getPhpVersionExtra() Gets the PHP version extra part. #### Return Value | | | | --- | --- | | string|null | The extra part | ### int getPhpArchitecture() #### Return Value | | | | --- | --- | | int | The PHP architecture as number of bits (e.g. 32 or 64) | ### string getPhpIntlLocale() #### Return Value | | | | --- | --- | | string | | ### string getPhpTimezone() #### Return Value | | | | --- | --- | | string | | ### string getAppName() Gets the application name. #### Return Value | | | | --- | --- | | string | The application name | ### string getEnv() Gets the environment. #### Return Value | | | | --- | --- | | string | The environment | ### bool isDebug() Returns true if the debug is enabled. #### Return Value | | | | --- | --- | | bool | true if debug is enabled, false otherwise | ### bool hasXDebug() Returns true if the XDebug is enabled. #### Return Value | | | | --- | --- | | bool | true if XDebug is enabled, false otherwise | ### bool hasApcu() Returns true if APCu is enabled. #### Return Value | | | | --- | --- | | bool | true if APCu is enabled, false otherwise | ### bool hasZendOpcache() Returns true if Zend OPcache is enabled. #### Return Value | | | | --- | --- | | bool | true if Zend OPcache is enabled, false otherwise | ### getBundles() ### string getSapiName() Gets the PHP SAPI name. #### Return Value | | | | --- | --- | | string | The environment | ### string getName() Returns the name of the collector. #### Return Value | | | | --- | --- | | string | The collector name | symfony AjaxDataCollector AjaxDataCollector ================== class **AjaxDataCollector** extends [DataCollector](datacollector "Symfony\Component\HttpKernel\DataCollector\DataCollector") AjaxDataCollector. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $data | | from [DataCollector](datacollector#property_data "Symfony\Component\HttpKernel\DataCollector\DataCollector") | Methods ------- | | | | | --- | --- | --- | | | [serialize](#method_serialize)() | from [DataCollector](datacollector#method_serialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [unserialize](#method_unserialize)($data) | from [DataCollector](datacollector#method_unserialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | [cloneVar](#method_cloneVar)(mixed $var) Converts the variable into a serializable Data instance. | from [DataCollector](datacollector#method_cloneVar "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | callable[] | [getCasters](#method_getCasters)() | from [DataCollector](datacollector#method_getCasters "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [collect](#method_collect)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. | | | | [reset](#method_reset)() Resets this data collector to its initial state. | | | string | [getName](#method_getName)() Returns the name of the collector. | | Details ------- ### serialize() ### unserialize($data) #### Parameters | | | | | --- | --- | --- | | | $data | | ### protected [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") cloneVar(mixed $var) Converts the variable into a serializable Data instance. This array can be displayed in the template using the VarDumper component. #### Parameters | | | | | --- | --- | --- | | mixed | $var | | #### Return Value | | | | --- | --- | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | | ### protected callable[] getCasters() #### Return Value | | | | --- | --- | | callable[] | The casters to add to the cloner | ### collect([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | | [Exception](http://php.net/Exception) | $exception | | ### reset() Resets this data collector to its initial state. ### string getName() Returns the name of the collector. #### Return Value | | | | --- | --- | | string | The collector name | symfony DataCollectorInterface DataCollectorInterface ======================= interface **DataCollectorInterface** DataCollectorInterface. Methods ------- | | | | | --- | --- | --- | | | [collect](#method_collect)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. | | | string | [getName](#method_getName)() Returns the name of the collector. | | | | [reset](#method_reset)() Resets this data collector to its initial state. | | Details ------- ### collect([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | | [Exception](http://php.net/Exception) | $exception | | ### string getName() Returns the name of the collector. #### Return Value | | | | --- | --- | | string | The collector name | ### reset() Resets this data collector to its initial state. symfony ExceptionDataCollector ExceptionDataCollector ======================= class **ExceptionDataCollector** extends [DataCollector](datacollector "Symfony\Component\HttpKernel\DataCollector\DataCollector") ExceptionDataCollector. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $data | | from [DataCollector](datacollector#property_data "Symfony\Component\HttpKernel\DataCollector\DataCollector") | Methods ------- | | | | | --- | --- | --- | | | [serialize](#method_serialize)() | from [DataCollector](datacollector#method_serialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [unserialize](#method_unserialize)($data) | from [DataCollector](datacollector#method_unserialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | [cloneVar](#method_cloneVar)(mixed $var) Converts the variable into a serializable Data instance. | from [DataCollector](datacollector#method_cloneVar "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | callable[] | [getCasters](#method_getCasters)() | from [DataCollector](datacollector#method_getCasters "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [collect](#method_collect)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. | | | | [reset](#method_reset)() Resets this data collector to its initial state. | | | bool | [hasException](#method_hasException)() Checks if the exception is not null. | | | [Exception](http://php.net/Exception) | [getException](#method_getException)() Gets the exception. | | | string | [getMessage](#method_getMessage)() Gets the exception message. | | | int | [getCode](#method_getCode)() Gets the exception code. | | | int | [getStatusCode](#method_getStatusCode)() Gets the status code. | | | array | [getTrace](#method_getTrace)() Gets the exception trace. | | | string | [getName](#method_getName)() Returns the name of the collector. | | Details ------- ### serialize() ### unserialize($data) #### Parameters | | | | | --- | --- | --- | | | $data | | ### protected [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") cloneVar(mixed $var) Converts the variable into a serializable Data instance. This array can be displayed in the template using the VarDumper component. #### Parameters | | | | | --- | --- | --- | | mixed | $var | | #### Return Value | | | | --- | --- | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | | ### protected callable[] getCasters() #### Return Value | | | | --- | --- | | callable[] | The casters to add to the cloner | ### collect([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | | [Exception](http://php.net/Exception) | $exception | | ### reset() Resets this data collector to its initial state. ### bool hasException() Checks if the exception is not null. #### Return Value | | | | --- | --- | | bool | true if the exception is not null, false otherwise | ### [Exception](http://php.net/Exception) getException() Gets the exception. #### Return Value | | | | --- | --- | | [Exception](http://php.net/Exception) | The exception | ### string getMessage() Gets the exception message. #### Return Value | | | | --- | --- | | string | The exception message | ### int getCode() Gets the exception code. #### Return Value | | | | --- | --- | | int | The exception code | ### int getStatusCode() Gets the status code. #### Return Value | | | | --- | --- | | int | The status code | ### array getTrace() Gets the exception trace. #### Return Value | | | | --- | --- | | array | The exception trace | ### string getName() Returns the name of the collector. #### Return Value | | | | --- | --- | | string | The collector name | symfony DumpDataCollector DumpDataCollector ================== class **DumpDataCollector** extends [DataCollector](datacollector "Symfony\Component\HttpKernel\DataCollector\DataCollector") implements [DataDumperInterface](../../vardumper/dumper/datadumperinterface "Symfony\Component\VarDumper\Dumper\DataDumperInterface") Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $data | | from [DataCollector](datacollector#property_data "Symfony\Component\HttpKernel\DataCollector\DataCollector") | Methods ------- | | | | | --- | --- | --- | | | [serialize](#method_serialize)() | | | | [unserialize](#method_unserialize)($data) | | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | [cloneVar](#method_cloneVar)(mixed $var) Converts the variable into a serializable Data instance. | from [DataCollector](datacollector#method_cloneVar "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | callable[] | [getCasters](#method_getCasters)() | from [DataCollector](datacollector#method_getCasters "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [\_\_construct](#method___construct)([Stopwatch](../../stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") $stopwatch = null, $fileLinkFormat = null, string $charset = null, [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack = null, $dumper = null) | | | | [\_\_clone](#method___clone)() | | | | [dump](#method_dump)([Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") $data) | | | | [collect](#method_collect)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. | | | | [reset](#method_reset)() Resets this data collector to its initial state. | | | | [getDumpsCount](#method_getDumpsCount)() | | | | [getDumps](#method_getDumps)($format, $maxDepthLimit = -1, $maxItemsPerDepth = -1) | | | string | [getName](#method_getName)() Returns the name of the collector. | | | | [\_\_destruct](#method___destruct)() | | Details ------- ### serialize() ### unserialize($data) #### Parameters | | | | | --- | --- | --- | | | $data | | ### protected [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") cloneVar(mixed $var) Converts the variable into a serializable Data instance. This array can be displayed in the template using the VarDumper component. #### Parameters | | | | | --- | --- | --- | | mixed | $var | | #### Return Value | | | | --- | --- | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | | ### protected callable[] getCasters() #### Return Value | | | | --- | --- | | callable[] | The casters to add to the cloner | ### \_\_construct([Stopwatch](../../stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") $stopwatch = null, $fileLinkFormat = null, string $charset = null, [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack = null, $dumper = null) #### Parameters | | | | | --- | --- | --- | | [Stopwatch](../../stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") | $stopwatch | | | | $fileLinkFormat | | | string | $charset | | | [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") | $requestStack | | | | $dumper | | ### \_\_clone() ### dump([Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") $data) #### Parameters | | | | | --- | --- | --- | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | $data | | ### collect([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | | [Exception](http://php.net/Exception) | $exception | | ### reset() Resets this data collector to its initial state. ### getDumpsCount() ### getDumps($format, $maxDepthLimit = -1, $maxItemsPerDepth = -1) #### Parameters | | | | | --- | --- | --- | | | $format | | | | $maxDepthLimit | | | | $maxItemsPerDepth | | ### string getName() Returns the name of the collector. #### Return Value | | | | --- | --- | | string | The collector name | ### \_\_destruct()
programming_docs
symfony DataCollector DataCollector ============== abstract class **DataCollector** implements [DataCollectorInterface](datacollectorinterface "Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface"), [Serializable](http://php.net/Serializable) DataCollector. Children of this class must store the collected data in the data property. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $data | | | Methods ------- | | | | | --- | --- | --- | | | [serialize](#method_serialize)() | | | | [unserialize](#method_unserialize)($data) | | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | [cloneVar](#method_cloneVar)(mixed $var) Converts the variable into a serializable Data instance. | | | callable[] | [getCasters](#method_getCasters)() | | Details ------- ### serialize() ### unserialize($data) #### Parameters | | | | | --- | --- | --- | | | $data | | ### protected [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") cloneVar(mixed $var) Converts the variable into a serializable Data instance. This array can be displayed in the template using the VarDumper component. #### Parameters | | | | | --- | --- | --- | | mixed | $var | | #### Return Value | | | | --- | --- | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | | ### protected callable[] getCasters() #### Return Value | | | | --- | --- | | callable[] | The casters to add to the cloner | symfony MemoryDataCollector MemoryDataCollector ==================== class **MemoryDataCollector** extends [DataCollector](datacollector "Symfony\Component\HttpKernel\DataCollector\DataCollector") implements [LateDataCollectorInterface](latedatacollectorinterface "Symfony\Component\HttpKernel\DataCollector\LateDataCollectorInterface") MemoryDataCollector. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $data | | from [DataCollector](datacollector#property_data "Symfony\Component\HttpKernel\DataCollector\DataCollector") | Methods ------- | | | | | --- | --- | --- | | | [serialize](#method_serialize)() | from [DataCollector](datacollector#method_serialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [unserialize](#method_unserialize)($data) | from [DataCollector](datacollector#method_unserialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | [cloneVar](#method_cloneVar)(mixed $var) Converts the variable into a serializable Data instance. | from [DataCollector](datacollector#method_cloneVar "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | callable[] | [getCasters](#method_getCasters)() | from [DataCollector](datacollector#method_getCasters "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [\_\_construct](#method___construct)() | | | | [collect](#method_collect)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. | | | | [reset](#method_reset)() Resets this data collector to its initial state. | | | | [lateCollect](#method_lateCollect)() Collects data as late as possible. | | | int | [getMemory](#method_getMemory)() Gets the memory. | | | int | [getMemoryLimit](#method_getMemoryLimit)() Gets the PHP memory limit. | | | | [updateMemoryUsage](#method_updateMemoryUsage)() Updates the memory usage data. | | | string | [getName](#method_getName)() Returns the name of the collector. | | Details ------- ### serialize() ### unserialize($data) #### Parameters | | | | | --- | --- | --- | | | $data | | ### protected [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") cloneVar(mixed $var) Converts the variable into a serializable Data instance. This array can be displayed in the template using the VarDumper component. #### Parameters | | | | | --- | --- | --- | | mixed | $var | | #### Return Value | | | | --- | --- | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | | ### protected callable[] getCasters() #### Return Value | | | | --- | --- | | callable[] | The casters to add to the cloner | ### \_\_construct() ### collect([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | | [Exception](http://php.net/Exception) | $exception | | ### reset() Resets this data collector to its initial state. ### lateCollect() Collects data as late as possible. ### int getMemory() Gets the memory. #### Return Value | | | | --- | --- | | int | The memory | ### int getMemoryLimit() Gets the PHP memory limit. #### Return Value | | | | --- | --- | | int | The memory limit | ### updateMemoryUsage() Updates the memory usage data. ### string getName() Returns the name of the collector. #### Return Value | | | | --- | --- | | string | The collector name | symfony RouterDataCollector RouterDataCollector ==================== class **RouterDataCollector** extends [DataCollector](datacollector "Symfony\Component\HttpKernel\DataCollector\DataCollector") RouterDataCollector. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $data | | from [DataCollector](datacollector#property_data "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | protected [SplObjectStorage](http://php.net/SplObjectStorage) | $controllers | | | Methods ------- | | | | | --- | --- | --- | | | [serialize](#method_serialize)() | from [DataCollector](datacollector#method_serialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [unserialize](#method_unserialize)($data) | from [DataCollector](datacollector#method_unserialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | [cloneVar](#method_cloneVar)(mixed $var) Converts the variable into a serializable Data instance. | from [DataCollector](datacollector#method_cloneVar "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | callable[] | [getCasters](#method_getCasters)() | from [DataCollector](datacollector#method_getCasters "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [\_\_construct](#method___construct)() | | | | [collect](#method_collect)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. | | | | [reset](#method_reset)() Resets this data collector to its initial state. | | | | [guessRoute](#method_guessRoute)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, $controller) | | | | [onKernelController](#method_onKernelController)([FilterControllerEvent](../event/filtercontrollerevent "Symfony\Component\HttpKernel\Event\FilterControllerEvent") $event) Remembers the controller associated to each request. | | | bool | [getRedirect](#method_getRedirect)() | | | string|null | [getTargetUrl](#method_getTargetUrl)() | | | string|null | [getTargetRoute](#method_getTargetRoute)() | | | string | [getName](#method_getName)() Returns the name of the collector. | | Details ------- ### serialize() ### unserialize($data) #### Parameters | | | | | --- | --- | --- | | | $data | | ### protected [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") cloneVar(mixed $var) Converts the variable into a serializable Data instance. This array can be displayed in the template using the VarDumper component. #### Parameters | | | | | --- | --- | --- | | mixed | $var | | #### Return Value | | | | --- | --- | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | | ### protected callable[] getCasters() #### Return Value | | | | --- | --- | | callable[] | The casters to add to the cloner | ### \_\_construct() ### collect([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | | [Exception](http://php.net/Exception) | $exception | | ### reset() Resets this data collector to its initial state. ### protected guessRoute([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, $controller) #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | | $controller | | ### onKernelController([FilterControllerEvent](../event/filtercontrollerevent "Symfony\Component\HttpKernel\Event\FilterControllerEvent") $event) Remembers the controller associated to each request. #### Parameters | | | | | --- | --- | --- | | [FilterControllerEvent](../event/filtercontrollerevent "Symfony\Component\HttpKernel\Event\FilterControllerEvent") | $event | | ### bool getRedirect() #### Return Value | | | | --- | --- | | bool | Whether this request will result in a redirect | ### string|null getTargetUrl() #### Return Value | | | | --- | --- | | string|null | The target URL | ### string|null getTargetRoute() #### Return Value | | | | --- | --- | | string|null | The target route | ### string getName() Returns the name of the collector. #### Return Value | | | | --- | --- | | string | The collector name | symfony RequestDataCollector RequestDataCollector ===================== class **RequestDataCollector** extends [DataCollector](datacollector "Symfony\Component\HttpKernel\DataCollector\DataCollector") implements [EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface"), [LateDataCollectorInterface](latedatacollectorinterface "Symfony\Component\HttpKernel\DataCollector\LateDataCollectorInterface") Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $data | | from [DataCollector](datacollector#property_data "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | protected | $controllers | | | Methods ------- | | | | | --- | --- | --- | | | [serialize](#method_serialize)() | from [DataCollector](datacollector#method_serialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [unserialize](#method_unserialize)($data) | from [DataCollector](datacollector#method_unserialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | [cloneVar](#method_cloneVar)(mixed $var) Converts the variable into a serializable Data instance. | from [DataCollector](datacollector#method_cloneVar "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | callable[] | [getCasters](#method_getCasters)() | from [DataCollector](datacollector#method_getCasters "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [\_\_construct](#method___construct)() | | | | [collect](#method_collect)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. | | | | [lateCollect](#method_lateCollect)() Collects data as late as possible. | | | | [reset](#method_reset)() Resets this data collector to its initial state. | | | | [getMethod](#method_getMethod)() | | | | [getPathInfo](#method_getPathInfo)() | | | | [getRequestRequest](#method_getRequestRequest)() | | | | [getRequestQuery](#method_getRequestQuery)() | | | | [getRequestHeaders](#method_getRequestHeaders)() | | | | [getRequestServer](#method_getRequestServer)($raw = false) | | | | [getRequestCookies](#method_getRequestCookies)($raw = false) | | | | [getRequestAttributes](#method_getRequestAttributes)() | | | | [getResponseHeaders](#method_getResponseHeaders)() | | | | [getResponseCookies](#method_getResponseCookies)() | | | | [getSessionMetadata](#method_getSessionMetadata)() | | | | [getSessionAttributes](#method_getSessionAttributes)() | | | | [getFlashes](#method_getFlashes)() | | | | [getContent](#method_getContent)() | | | | [getContentType](#method_getContentType)() | | | | [getStatusText](#method_getStatusText)() | | | | [getStatusCode](#method_getStatusCode)() | | | | [getFormat](#method_getFormat)() | | | | [getLocale](#method_getLocale)() | | | | [getDotenvVars](#method_getDotenvVars)() | | | string | [getRoute](#method_getRoute)() Gets the route name. | | | | [getIdentifier](#method_getIdentifier)() | | | array | [getRouteParams](#method_getRouteParams)() Gets the route parameters. | | | array|string | [getController](#method_getController)() Gets the parsed controller. | | | array|bool | [getRedirect](#method_getRedirect)() Gets the previous request attributes. | | | | [getForwardToken](#method_getForwardToken)() | | | | [onKernelController](#method_onKernelController)([FilterControllerEvent](../event/filtercontrollerevent "Symfony\Component\HttpKernel\Event\FilterControllerEvent") $event) | | | | [onKernelResponse](#method_onKernelResponse)([FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) | | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | | | string | [getName](#method_getName)() Returns the name of the collector. | | | array|string | [parseController](#method_parseController)(mixed $controller) Parse a controller. | | Details ------- ### serialize() ### unserialize($data) #### Parameters | | | | | --- | --- | --- | | | $data | | ### protected [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") cloneVar(mixed $var) Converts the variable into a serializable Data instance. This array can be displayed in the template using the VarDumper component. #### Parameters | | | | | --- | --- | --- | | mixed | $var | | #### Return Value | | | | --- | --- | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | | ### protected callable[] getCasters() #### Return Value | | | | --- | --- | | callable[] | The casters to add to the cloner | ### \_\_construct() ### collect([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | | [Exception](http://php.net/Exception) | $exception | | ### lateCollect() Collects data as late as possible. ### reset() Resets this data collector to its initial state. ### getMethod() ### getPathInfo() ### getRequestRequest() ### getRequestQuery() ### getRequestHeaders() ### getRequestServer($raw = false) #### Parameters | | | | | --- | --- | --- | | | $raw | | ### getRequestCookies($raw = false) #### Parameters | | | | | --- | --- | --- | | | $raw | | ### getRequestAttributes() ### getResponseHeaders() ### getResponseCookies() ### getSessionMetadata() ### getSessionAttributes() ### getFlashes() ### getContent() ### getContentType() ### getStatusText() ### getStatusCode() ### getFormat() ### getLocale() ### getDotenvVars() ### string getRoute() Gets the route name. The \_route request attributes is automatically set by the Router Matcher. #### Return Value | | | | --- | --- | | string | The route | ### getIdentifier() ### array getRouteParams() Gets the route parameters. The \_route\_params request attributes is automatically set by the RouterListener. #### Return Value | | | | --- | --- | | array | The parameters | ### array|string getController() Gets the parsed controller. #### Return Value | | | | --- | --- | | array|string | The controller as a string or array of data with keys 'class', 'method', 'file' and 'line' | ### array|bool getRedirect() Gets the previous request attributes. #### Return Value | | | | --- | --- | | array|bool | A legacy array of data from the previous redirection response or false otherwise | ### getForwardToken() ### onKernelController([FilterControllerEvent](../event/filtercontrollerevent "Symfony\Component\HttpKernel\Event\FilterControllerEvent") $event) #### Parameters | | | | | --- | --- | --- | | [FilterControllerEvent](../event/filtercontrollerevent "Symfony\Component\HttpKernel\Event\FilterControllerEvent") | $event | | ### onKernelResponse([FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) #### Parameters | | | | | --- | --- | --- | | [FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") | $event | | ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to | ### string getName() Returns the name of the collector. #### Return Value | | | | --- | --- | | string | The collector name | ### protected array|string parseController(mixed $controller) Parse a controller. #### Parameters | | | | | --- | --- | --- | | mixed | $controller | The controller to parse | #### Return Value | | | | --- | --- | | array|string | An array of controller data or a simple string |
programming_docs
symfony LateDataCollectorInterface LateDataCollectorInterface =========================== interface **LateDataCollectorInterface** LateDataCollectorInterface. Methods ------- | | | | | --- | --- | --- | | | [lateCollect](#method_lateCollect)() Collects data as late as possible. | | Details ------- ### lateCollect() Collects data as late as possible. symfony LoggerDataCollector LoggerDataCollector ==================== class **LoggerDataCollector** extends [DataCollector](datacollector "Symfony\Component\HttpKernel\DataCollector\DataCollector") implements [LateDataCollectorInterface](latedatacollectorinterface "Symfony\Component\HttpKernel\DataCollector\LateDataCollectorInterface") LogDataCollector. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $data | | from [DataCollector](datacollector#property_data "Symfony\Component\HttpKernel\DataCollector\DataCollector") | Methods ------- | | | | | --- | --- | --- | | | [serialize](#method_serialize)() | from [DataCollector](datacollector#method_serialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [unserialize](#method_unserialize)($data) | from [DataCollector](datacollector#method_unserialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | [cloneVar](#method_cloneVar)(mixed $var) Converts the variable into a serializable Data instance. | from [DataCollector](datacollector#method_cloneVar "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | callable[] | [getCasters](#method_getCasters)() | from [DataCollector](datacollector#method_getCasters "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [\_\_construct](#method___construct)($logger = null, string $containerPathPrefix = null, [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack = null) | | | | [collect](#method_collect)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. | | | | [reset](#method_reset)() Resets this data collector to its initial state. | | | | [lateCollect](#method_lateCollect)() Collects data as late as possible. | | | array | [getLogs](#method_getLogs)() Gets the logs. | | | | [getPriorities](#method_getPriorities)() | | | | [countErrors](#method_countErrors)() | | | | [countDeprecations](#method_countDeprecations)() | | | | [countWarnings](#method_countWarnings)() | | | | [countScreams](#method_countScreams)() | | | | [getCompilerLogs](#method_getCompilerLogs)() | | | string | [getName](#method_getName)() Returns the name of the collector. | | Details ------- ### serialize() ### unserialize($data) #### Parameters | | | | | --- | --- | --- | | | $data | | ### protected [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") cloneVar(mixed $var) Converts the variable into a serializable Data instance. This array can be displayed in the template using the VarDumper component. #### Parameters | | | | | --- | --- | --- | | mixed | $var | | #### Return Value | | | | --- | --- | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | | ### protected callable[] getCasters() #### Return Value | | | | --- | --- | | callable[] | The casters to add to the cloner | ### \_\_construct($logger = null, string $containerPathPrefix = null, [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack = null) #### Parameters | | | | | --- | --- | --- | | | $logger | | | string | $containerPathPrefix | | | [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") | $requestStack | | ### collect([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | | [Exception](http://php.net/Exception) | $exception | | ### reset() Resets this data collector to its initial state. ### lateCollect() Collects data as late as possible. ### array getLogs() Gets the logs. #### Return Value | | | | --- | --- | | array | An array of logs | ### getPriorities() ### countErrors() ### countDeprecations() ### countWarnings() ### countScreams() ### getCompilerLogs() ### string getName() Returns the name of the collector. #### Return Value | | | | --- | --- | | string | The collector name | symfony TimeDataCollector TimeDataCollector ================== class **TimeDataCollector** extends [DataCollector](datacollector "Symfony\Component\HttpKernel\DataCollector\DataCollector") implements [LateDataCollectorInterface](latedatacollectorinterface "Symfony\Component\HttpKernel\DataCollector\LateDataCollectorInterface") TimeDataCollector. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $data | | from [DataCollector](datacollector#property_data "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | protected | $kernel | | | | protected | $stopwatch | | | Methods ------- | | | | | --- | --- | --- | | | [serialize](#method_serialize)() | from [DataCollector](datacollector#method_serialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [unserialize](#method_unserialize)($data) | from [DataCollector](datacollector#method_unserialize "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | [cloneVar](#method_cloneVar)(mixed $var) Converts the variable into a serializable Data instance. | from [DataCollector](datacollector#method_cloneVar "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | callable[] | [getCasters](#method_getCasters)() | from [DataCollector](datacollector#method_getCasters "Symfony\Component\HttpKernel\DataCollector\DataCollector") | | | [\_\_construct](#method___construct)([KernelInterface](../kernelinterface "Symfony\Component\HttpKernel\KernelInterface") $kernel = null, [Stopwatch](../../stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") $stopwatch = null) | | | | [collect](#method_collect)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. | | | | [reset](#method_reset)() Resets this data collector to its initial state. | | | | [lateCollect](#method_lateCollect)() Collects data as late as possible. | | | | [setEvents](#method_setEvents)(array $events) Sets the request events. | | | array | [getEvents](#method_getEvents)() Gets the request events. | | | float | [getDuration](#method_getDuration)() Gets the request elapsed time. | | | float | [getInitTime](#method_getInitTime)() Gets the initialization time. | | | int | [getStartTime](#method_getStartTime)() Gets the request time. | | | string | [getName](#method_getName)() Returns the name of the collector. | | Details ------- ### serialize() ### unserialize($data) #### Parameters | | | | | --- | --- | --- | | | $data | | ### protected [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") cloneVar(mixed $var) Converts the variable into a serializable Data instance. This array can be displayed in the template using the VarDumper component. #### Parameters | | | | | --- | --- | --- | | mixed | $var | | #### Return Value | | | | --- | --- | | [Data](../../vardumper/cloner/data "Symfony\Component\VarDumper\Cloner\Data") | | ### protected callable[] getCasters() #### Return Value | | | | --- | --- | | callable[] | The casters to add to the cloner | ### \_\_construct([KernelInterface](../kernelinterface "Symfony\Component\HttpKernel\KernelInterface") $kernel = null, [Stopwatch](../../stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") $stopwatch = null) #### Parameters | | | | | --- | --- | --- | | [KernelInterface](../kernelinterface "Symfony\Component\HttpKernel\KernelInterface") | $kernel | | | [Stopwatch](../../stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") | $stopwatch | | ### collect([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Request and Response. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | | [Exception](http://php.net/Exception) | $exception | | ### reset() Resets this data collector to its initial state. ### lateCollect() Collects data as late as possible. ### setEvents(array $events) Sets the request events. #### Parameters | | | | | --- | --- | --- | | array | $events | The request events | ### array getEvents() Gets the request events. #### Return Value | | | | --- | --- | | array | The request events | ### float getDuration() Gets the request elapsed time. #### Return Value | | | | --- | --- | | float | The elapsed time | ### float getInitTime() Gets the initialization time. This is the time spent until the beginning of the request handling. #### Return Value | | | | --- | --- | | float | The elapsed time | ### int getStartTime() Gets the request time. #### Return Value | | | | --- | --- | | int | The time | ### string getName() Returns the name of the collector. #### Return Value | | | | --- | --- | | string | The collector name | symfony ArgumentMetadata ArgumentMetadata ================= class **ArgumentMetadata** Responsible for storing metadata of an argument. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $name, string|null $type, bool $isVariadic, bool $hasDefaultValue, $defaultValue, bool $isNullable = false) | | | string | [getName](#method_getName)() Returns the name as given in PHP, $foo would yield "foo". | | | string | [getType](#method_getType)() Returns the type of the argument. | | | bool | [isVariadic](#method_isVariadic)() Returns whether the argument is defined as ". | | | bool | [hasDefaultValue](#method_hasDefaultValue)() Returns whether the argument has a default value. | | | bool | [isNullable](#method_isNullable)() Returns whether the argument accepts null values. | | | mixed | [getDefaultValue](#method_getDefaultValue)() Returns the default value of the argument. | | Details ------- ### \_\_construct(string $name, string|null $type, bool $isVariadic, bool $hasDefaultValue, $defaultValue, bool $isNullable = false) #### Parameters | | | | | --- | --- | --- | | string | $name | | | string|null | $type | | | bool | $isVariadic | | | bool | $hasDefaultValue | | | | $defaultValue | | | bool | $isNullable | | ### string getName() Returns the name as given in PHP, $foo would yield "foo". #### Return Value | | | | --- | --- | | string | | ### string getType() Returns the type of the argument. The type is the PHP class in 5.5+ and additionally the basic type in PHP 7.0+. #### Return Value | | | | --- | --- | | string | | ### bool isVariadic() Returns whether the argument is defined as ". ..$variadic". #### Return Value | | | | --- | --- | | bool | | ### bool hasDefaultValue() Returns whether the argument has a default value. Implies whether an argument is optional. #### Return Value | | | | --- | --- | | bool | | ### bool isNullable() Returns whether the argument accepts null values. #### Return Value | | | | --- | --- | | bool | | ### mixed getDefaultValue() Returns the default value of the argument. #### Return Value | | | | --- | --- | | mixed | | #### Exceptions | | | | --- | --- | | [LogicException](http://php.net/LogicException) | if no default value is present; {see self::hasDefaultValue()} | symfony ArgumentMetadataFactory ArgumentMetadataFactory ======================== class **ArgumentMetadataFactory** implements [ArgumentMetadataFactoryInterface](argumentmetadatafactoryinterface "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadataFactoryInterface") Builds {see ArgumentMetadata} objects based on the given Controller. Methods ------- | | | | | --- | --- | --- | | [ArgumentMetadata](argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata")[] | [createArgumentMetadata](#method_createArgumentMetadata)(mixed $controller) | | Details ------- ### [ArgumentMetadata](argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata")[] createArgumentMetadata(mixed $controller) #### Parameters | | | | | --- | --- | --- | | mixed | $controller | The controller to resolve the arguments for | #### Return Value | | | | --- | --- | | [ArgumentMetadata](argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata")[] | | symfony ArgumentMetadataFactoryInterface ArgumentMetadataFactoryInterface ================================= interface **ArgumentMetadataFactoryInterface** Builds method argument data. Methods ------- | | | | | --- | --- | --- | | [ArgumentMetadata](argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata")[] | [createArgumentMetadata](#method_createArgumentMetadata)(mixed $controller) | | Details ------- ### [ArgumentMetadata](argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata")[] createArgumentMetadata(mixed $controller) #### Parameters | | | | | --- | --- | --- | | mixed | $controller | The controller to resolve the arguments for | #### Return Value | | | | --- | --- | | [ArgumentMetadata](argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata")[] | | symfony FileLocator FileLocator ============ class **FileLocator** extends [FileLocator](../../config/filelocator "Symfony\Component\Config\FileLocator") FileLocator uses the KernelInterface to locate resources in bundles. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $paths | | from [FileLocator](../../config/filelocator#property_paths "Symfony\Component\Config\FileLocator") | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([KernelInterface](../kernelinterface "Symfony\Component\HttpKernel\KernelInterface") $kernel, string $path = null, string|string[] $paths = array()) | | | string|array | [locate](#method_locate)($file, string|null $currentPath = null, bool $first = true) Returns a full path for a given file name. | | Details ------- ### \_\_construct([KernelInterface](../kernelinterface "Symfony\Component\HttpKernel\KernelInterface") $kernel, string $path = null, string|string[] $paths = array()) #### Parameters | | | | | --- | --- | --- | | [KernelInterface](../kernelinterface "Symfony\Component\HttpKernel\KernelInterface") | $kernel | A KernelInterface instance | | string | $path | The path the global resource directory | | string|string[] | $paths | A path or an array of paths where to look for resources | ### string|array locate($file, string|null $currentPath = null, bool $first = true) Returns a full path for a given file name. #### Parameters | | | | | --- | --- | --- | | | $file | | | string|null | $currentPath | The current path | | bool | $first | Whether to return the first occurrence or an array of filenames | #### Return Value | | | | --- | --- | | string|array | The full path to the file or an array of file paths | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](http://php.net/InvalidArgumentException) | If $name is empty | | [FileLocatorFileNotFoundException](../../config/exception/filelocatorfilenotfoundexception "Symfony\Component\Config\Exception\FileLocatorFileNotFoundException") | If a file is not found | symfony ChainCacheClearer ChainCacheClearer ================== class **ChainCacheClearer** implements [CacheClearerInterface](cacheclearerinterface "Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface") ChainCacheClearer. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(iterable $clearers = array()) | | | | [clear](#method_clear)(string $cacheDir) Clears any caches necessary. | | Details ------- ### \_\_construct(iterable $clearers = array()) #### Parameters | | | | | --- | --- | --- | | iterable | $clearers | | ### clear(string $cacheDir) Clears any caches necessary. #### Parameters | | | | | --- | --- | --- | | string | $cacheDir | The cache directory | symfony CacheClearerInterface CacheClearerInterface ====================== interface **CacheClearerInterface** CacheClearerInterface. Methods ------- | | | | | --- | --- | --- | | | [clear](#method_clear)(string $cacheDir) Clears any caches necessary. | | Details ------- ### clear(string $cacheDir) Clears any caches necessary. #### Parameters | | | | | --- | --- | --- | | string | $cacheDir | The cache directory | symfony Psr6CacheClearer Psr6CacheClearer ================= class **Psr6CacheClearer** implements [CacheClearerInterface](cacheclearerinterface "Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface") Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(array $pools = array()) | | | | [hasPool](#method_hasPool)($name) | | | | [getPool](#method_getPool)($name) | | | | [clearPool](#method_clearPool)($name) | | | | [clear](#method_clear)(string $cacheDir) Clears any caches necessary. | | Details ------- ### \_\_construct(array $pools = array()) #### Parameters | | | | | --- | --- | --- | | array | $pools | | ### hasPool($name) #### Parameters | | | | | --- | --- | --- | | | $name | | ### getPool($name) #### Parameters | | | | | --- | --- | --- | | | $name | | ### clearPool($name) #### Parameters | | | | | --- | --- | --- | | | $name | | ### clear(string $cacheDir) Clears any caches necessary. #### Parameters | | | | | --- | --- | --- | | string | $cacheDir | The cache directory | symfony CacheWarmerInterface CacheWarmerInterface ===================== interface **CacheWarmerInterface** implements [WarmableInterface](warmableinterface "Symfony\Component\HttpKernel\CacheWarmer\WarmableInterface") Interface for classes able to warm up the cache. Methods ------- | | | | | --- | --- | --- | | | [warmUp](#method_warmUp)(string $cacheDir) Warms up the cache. | from [WarmableInterface](warmableinterface#method_warmUp "Symfony\Component\HttpKernel\CacheWarmer\WarmableInterface") | | bool | [isOptional](#method_isOptional)() Checks whether this warmer is optional or not. | | Details ------- ### warmUp(string $cacheDir) Warms up the cache. #### Parameters | | | | | --- | --- | --- | | string | $cacheDir | The cache directory | ### bool isOptional() Checks whether this warmer is optional or not. Optional warmers can be ignored on certain conditions. A warmer should return true if the cache can be generated incrementally and on-demand. #### Return Value | | | | --- | --- | | bool | true if the warmer is optional, false otherwise |
programming_docs
symfony CacheWarmerAggregate CacheWarmerAggregate ===================== class **CacheWarmerAggregate** implements [CacheWarmerInterface](cachewarmerinterface "Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface") Aggregates several cache warmers into a single one. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(iterable $warmers = array()) | | | | [enableOptionalWarmers](#method_enableOptionalWarmers)() | | | | [enableOnlyOptionalWarmers](#method_enableOnlyOptionalWarmers)() | | | | [warmUp](#method_warmUp)(string $cacheDir) Warms up the cache. | | | bool | [isOptional](#method_isOptional)() Checks whether this warmer is optional or not. | | Details ------- ### \_\_construct(iterable $warmers = array()) #### Parameters | | | | | --- | --- | --- | | iterable | $warmers | | ### enableOptionalWarmers() ### enableOnlyOptionalWarmers() ### warmUp(string $cacheDir) Warms up the cache. #### Parameters | | | | | --- | --- | --- | | string | $cacheDir | The cache directory | ### bool isOptional() Checks whether this warmer is optional or not. #### Return Value | | | | --- | --- | | bool | true if the warmer is optional, false otherwise | symfony CacheWarmer CacheWarmer ============ abstract class **CacheWarmer** implements [CacheWarmerInterface](cachewarmerinterface "Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface") Abstract cache warmer that knows how to write a file to the cache. Methods ------- | | | | | --- | --- | --- | | | [writeCacheFile](#method_writeCacheFile)($file, $content) | | Details ------- ### protected writeCacheFile($file, $content) #### Parameters | | | | | --- | --- | --- | | | $file | | | | $content | | symfony WarmableInterface WarmableInterface ================== interface **WarmableInterface** Interface for classes that support warming their cache. Methods ------- | | | | | --- | --- | --- | | | [warmUp](#method_warmUp)(string $cacheDir) Warms up the cache. | | Details ------- ### warmUp(string $cacheDir) Warms up the cache. #### Parameters | | | | | --- | --- | --- | | string | $cacheDir | The cache directory | symfony BundleInterface BundleInterface ================ interface **BundleInterface** implements [ContainerAwareInterface](../../dependencyinjection/containerawareinterface "Symfony\Component\DependencyInjection\ContainerAwareInterface") BundleInterface. Methods ------- | | | | | --- | --- | --- | | | [setContainer](#method_setContainer)([ContainerInterface](../../dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface") $container = null) Sets the container. | from [ContainerAwareInterface](../../dependencyinjection/containerawareinterface#method_setContainer "Symfony\Component\DependencyInjection\ContainerAwareInterface") | | | [boot](#method_boot)() Boots the Bundle. | | | | [shutdown](#method_shutdown)() Shutdowns the Bundle. | | | | [build](#method_build)([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Builds the bundle. | | | [ExtensionInterface](../../dependencyinjection/extension/extensioninterface "Symfony\Component\DependencyInjection\Extension\ExtensionInterface")|null | [getContainerExtension](#method_getContainerExtension)() Returns the container extension that should be implicitly loaded. | | | string | [getName](#method_getName)() Returns the bundle name (the class short name). | | | string | [getNamespace](#method_getNamespace)() Gets the Bundle namespace. | | | string | [getPath](#method_getPath)() Gets the Bundle directory path. | | Details ------- ### setContainer([ContainerInterface](../../dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface") $container = null) Sets the container. #### Parameters | | | | | --- | --- | --- | | [ContainerInterface](../../dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface") | $container | | ### boot() Boots the Bundle. ### shutdown() Shutdowns the Bundle. ### build([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Builds the bundle. It is only ever called once when the cache is empty. #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | ### [ExtensionInterface](../../dependencyinjection/extension/extensioninterface "Symfony\Component\DependencyInjection\Extension\ExtensionInterface")|null getContainerExtension() Returns the container extension that should be implicitly loaded. #### Return Value | | | | --- | --- | | [ExtensionInterface](../../dependencyinjection/extension/extensioninterface "Symfony\Component\DependencyInjection\Extension\ExtensionInterface")|null | The default extension or null if there is none | ### string getName() Returns the bundle name (the class short name). #### Return Value | | | | --- | --- | | string | The Bundle name | ### string getNamespace() Gets the Bundle namespace. #### Return Value | | | | --- | --- | | string | The Bundle namespace | ### string getPath() Gets the Bundle directory path. The path should always be returned as a Unix path (with /). #### Return Value | | | | --- | --- | | string | The Bundle absolute path | symfony Bundle Bundle ======= abstract class **Bundle** implements [BundleInterface](bundleinterface "Symfony\Component\HttpKernel\Bundle\BundleInterface") An implementation of BundleInterface that adds a few conventions for DependencyInjection extensions and Console commands. Traits ------ | | | | --- | --- | | [ContainerAwareTrait](../../dependencyinjection/containerawaretrait "Symfony\Component\DependencyInjection\ContainerAwareTrait") | ContainerAware trait. | Properties ---------- | | | | | | --- | --- | --- | --- | | protected [ContainerInterface](../../dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface") | $container | | from [ContainerAwareTrait](../../dependencyinjection/containerawaretrait#property_container "Symfony\Component\DependencyInjection\ContainerAwareTrait") | | protected | $name | | | | protected | $extension | | | | protected | $path | | | Methods ------- | | | | | --- | --- | --- | | | [setContainer](#method_setContainer)([ContainerInterface](../../dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface") $container = null) | from [ContainerAwareTrait](../../dependencyinjection/containerawaretrait#method_setContainer "Symfony\Component\DependencyInjection\ContainerAwareTrait") | | | [boot](#method_boot)() Boots the Bundle. | | | | [shutdown](#method_shutdown)() Shutdowns the Bundle. | | | | [build](#method_build)([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Builds the bundle. | | | [ExtensionInterface](../../dependencyinjection/extension/extensioninterface "Symfony\Component\DependencyInjection\Extension\ExtensionInterface")|null | [getContainerExtension](#method_getContainerExtension)() Returns the bundle's container extension. | | | string | [getNamespace](#method_getNamespace)() Gets the Bundle namespace. | | | string | [getPath](#method_getPath)() Gets the Bundle directory path. | | | string | [getName](#method_getName)() Returns the bundle name (the class short name). | | | | [registerCommands](#method_registerCommands)([Application](../../console/application "Symfony\Component\Console\Application") $application) | | | string | [getContainerExtensionClass](#method_getContainerExtensionClass)() Returns the bundle's container extension class. | | | [ExtensionInterface](../../dependencyinjection/extension/extensioninterface "Symfony\Component\DependencyInjection\Extension\ExtensionInterface")|null | [createContainerExtension](#method_createContainerExtension)() Creates the bundle's container extension. | | Details ------- ### setContainer([ContainerInterface](../../dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface") $container = null) #### Parameters | | | | | --- | --- | --- | | [ContainerInterface](../../dependencyinjection/containerinterface "Symfony\Component\DependencyInjection\ContainerInterface") | $container | | ### boot() Boots the Bundle. ### shutdown() Shutdowns the Bundle. ### build([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Builds the bundle. It is only ever called once when the cache is empty. #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | ### [ExtensionInterface](../../dependencyinjection/extension/extensioninterface "Symfony\Component\DependencyInjection\Extension\ExtensionInterface")|null getContainerExtension() Returns the bundle's container extension. #### Return Value | | | | --- | --- | | [ExtensionInterface](../../dependencyinjection/extension/extensioninterface "Symfony\Component\DependencyInjection\Extension\ExtensionInterface")|null | The default extension or null if there is none | #### Exceptions | | | | --- | --- | | [LogicException](http://php.net/LogicException) | | ### string getNamespace() Gets the Bundle namespace. #### Return Value | | | | --- | --- | | string | The Bundle namespace | ### string getPath() Gets the Bundle directory path. The path should always be returned as a Unix path (with /). #### Return Value | | | | --- | --- | | string | The Bundle absolute path | ### final string getName() Returns the bundle name (the class short name). #### Return Value | | | | --- | --- | | string | The Bundle name | ### registerCommands([Application](../../console/application "Symfony\Component\Console\Application") $application) #### Parameters | | | | | --- | --- | --- | | [Application](../../console/application "Symfony\Component\Console\Application") | $application | | ### protected string getContainerExtensionClass() Returns the bundle's container extension class. #### Return Value | | | | --- | --- | | string | | ### protected [ExtensionInterface](../../dependencyinjection/extension/extensioninterface "Symfony\Component\DependencyInjection\Extension\ExtensionInterface")|null createContainerExtension() Creates the bundle's container extension. #### Return Value | | | | --- | --- | | [ExtensionInterface](../../dependencyinjection/extension/extensioninterface "Symfony\Component\DependencyInjection\Extension\ExtensionInterface")|null | | symfony ControllerReference ControllerReference ==================== class **ControllerReference** Acts as a marker and a data holder for a Controller. Some methods in Symfony accept both a URI (as a string) or a controller as an argument. In the latter case, instead of passing an array representing the controller, you can use an instance of this class. Properties ---------- | | | | | | --- | --- | --- | --- | | | $controller | | | | | $attributes | | | | | $query | | | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $controller, array $attributes = array(), array $query = array()) | | Details ------- ### \_\_construct(string $controller, array $attributes = array(), array $query = array()) #### Parameters | | | | | --- | --- | --- | | string | $controller | The controller name | | array | $attributes | An array of parameters to add to the Request attributes | | array | $query | An array of parameters to add to the Request query string | symfony ControllerResolver ControllerResolver =================== class **ControllerResolver** implements [ControllerResolverInterface](controllerresolverinterface "Symfony\Component\HttpKernel\Controller\ControllerResolverInterface") This implementation uses the '\_controller' request attribute to determine the controller to execute. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(LoggerInterface $logger = null) | | | callable|false | [getController](#method_getController)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Returns the Controller instance associated with a Request. | | | callable | [createController](#method_createController)(string $controller) Returns a callable for the given controller. | | | object | [instantiateController](#method_instantiateController)(string $class) Returns an instantiated controller. | | Details ------- ### \_\_construct(LoggerInterface $logger = null) #### Parameters | | | | | --- | --- | --- | | LoggerInterface | $logger | | ### callable|false getController([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Returns the Controller instance associated with a Request. As several resolvers can exist for a single application, a resolver must return false when it is not able to determine the controller. The resolver must only throw an exception when it should be able to load controller but cannot because of some errors made by the developer. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | #### Return Value | | | | --- | --- | | callable|false | A PHP callable representing the Controller, or false if this resolver is not able to determine the controller | #### Exceptions | | | | --- | --- | | [LogicException](http://php.net/LogicException) | If a controller was found based on the request but it is not callable | ### protected callable createController(string $controller) Returns a callable for the given controller. #### Parameters | | | | | --- | --- | --- | | string | $controller | A Controller string | #### Return Value | | | | --- | --- | | callable | A PHP callable | ### protected object instantiateController(string $class) Returns an instantiated controller. #### Parameters | | | | | --- | --- | --- | | string | $class | A class name | #### Return Value | | | | --- | --- | | object | | symfony TraceableArgumentResolver TraceableArgumentResolver ========================== class **TraceableArgumentResolver** implements [ArgumentResolverInterface](argumentresolverinterface "Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface") Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([ArgumentResolverInterface](argumentresolverinterface "Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface") $resolver, [Stopwatch](../../stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") $stopwatch) | | | array | [getArguments](#method_getArguments)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, callable $controller) Returns the arguments to pass to the controller. | | Details ------- ### \_\_construct([ArgumentResolverInterface](argumentresolverinterface "Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface") $resolver, [Stopwatch](../../stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") $stopwatch) #### Parameters | | | | | --- | --- | --- | | [ArgumentResolverInterface](argumentresolverinterface "Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface") | $resolver | | | [Stopwatch](../../stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") | $stopwatch | | ### array getArguments([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, callable $controller) Returns the arguments to pass to the controller. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | callable | $controller | | #### Return Value | | | | --- | --- | | array | An array of arguments to pass to the controller | #### Exceptions | | | | --- | --- | | [RuntimeException](http://php.net/RuntimeException) | When no value could be provided for a required argument | symfony TraceableControllerResolver TraceableControllerResolver ============================ class **TraceableControllerResolver** implements [ControllerResolverInterface](controllerresolverinterface "Symfony\Component\HttpKernel\Controller\ControllerResolverInterface") Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([ControllerResolverInterface](controllerresolverinterface "Symfony\Component\HttpKernel\Controller\ControllerResolverInterface") $resolver, [Stopwatch](../../stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") $stopwatch) | | | callable|false | [getController](#method_getController)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Returns the Controller instance associated with a Request. | | Details ------- ### \_\_construct([ControllerResolverInterface](controllerresolverinterface "Symfony\Component\HttpKernel\Controller\ControllerResolverInterface") $resolver, [Stopwatch](../../stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") $stopwatch) #### Parameters | | | | | --- | --- | --- | | [ControllerResolverInterface](controllerresolverinterface "Symfony\Component\HttpKernel\Controller\ControllerResolverInterface") | $resolver | | | [Stopwatch](../../stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") | $stopwatch | | ### callable|false getController([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Returns the Controller instance associated with a Request. As several resolvers can exist for a single application, a resolver must return false when it is not able to determine the controller. The resolver must only throw an exception when it should be able to load controller but cannot because of some errors made by the developer. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | #### Return Value | | | | --- | --- | | callable|false | A PHP callable representing the Controller, or false if this resolver is not able to determine the controller | #### Exceptions | | | | --- | --- | | [LogicException](http://php.net/LogicException) | If a controller was found based on the request but it is not callable | symfony ContainerControllerResolver ContainerControllerResolver ============================ class **ContainerControllerResolver** extends [ControllerResolver](controllerresolver "Symfony\Component\HttpKernel\Controller\ControllerResolver") A controller resolver searching for a controller in a psr-11 container when using the "service:method" notation. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $container | | | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(ContainerInterface $container, LoggerInterface $logger = null) | | | callable|false | [getController](#method_getController)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Returns the Controller instance associated with a Request. | from [ControllerResolver](controllerresolver#method_getController "Symfony\Component\HttpKernel\Controller\ControllerResolver") | | callable | [createController](#method_createController)(string $controller) Returns a callable for the given controller. | | | object | [instantiateController](#method_instantiateController)(string $class) Returns an instantiated controller. | | Details ------- ### \_\_construct(ContainerInterface $container, LoggerInterface $logger = null) #### Parameters | | | | | --- | --- | --- | | ContainerInterface | $container | | | LoggerInterface | $logger | | ### callable|false getController([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Returns the Controller instance associated with a Request. As several resolvers can exist for a single application, a resolver must return false when it is not able to determine the controller. The resolver must only throw an exception when it should be able to load controller but cannot because of some errors made by the developer. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | #### Return Value | | | | --- | --- | | callable|false | A PHP callable representing the Controller, or false if this resolver is not able to determine the controller | #### Exceptions | | | | --- | --- | | [LogicException](http://php.net/LogicException) | If a controller was found based on the request but it is not callable | ### protected callable createController(string $controller) Returns a callable for the given controller. #### Parameters | | | | | --- | --- | --- | | string | $controller | A Controller string | #### Return Value | | | | --- | --- | | callable | A PHP callable | ### protected object instantiateController(string $class) Returns an instantiated controller. #### Parameters | | | | | --- | --- | --- | | string | $class | A class name | #### Return Value | | | | --- | --- | | object | |
programming_docs
symfony ControllerResolverInterface ControllerResolverInterface ============================ interface **ControllerResolverInterface** A ControllerResolverInterface implementation knows how to determine the controller to execute based on a Request object. A Controller can be any valid PHP callable. Methods ------- | | | | | --- | --- | --- | | callable|false | [getController](#method_getController)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Returns the Controller instance associated with a Request. | | Details ------- ### callable|false getController([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Returns the Controller instance associated with a Request. As several resolvers can exist for a single application, a resolver must return false when it is not able to determine the controller. The resolver must only throw an exception when it should be able to load controller but cannot because of some errors made by the developer. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | #### Return Value | | | | --- | --- | | callable|false | A PHP callable representing the Controller, or false if this resolver is not able to determine the controller | #### Exceptions | | | | --- | --- | | [LogicException](http://php.net/LogicException) | If a controller was found based on the request but it is not callable | symfony ArgumentResolverInterface ArgumentResolverInterface ========================== interface **ArgumentResolverInterface** An ArgumentResolverInterface instance knows how to determine the arguments for a specific action. Methods ------- | | | | | --- | --- | --- | | array | [getArguments](#method_getArguments)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, callable $controller) Returns the arguments to pass to the controller. | | Details ------- ### array getArguments([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, callable $controller) Returns the arguments to pass to the controller. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | callable | $controller | | #### Return Value | | | | --- | --- | | array | An array of arguments to pass to the controller | #### Exceptions | | | | --- | --- | | [RuntimeException](http://php.net/RuntimeException) | When no value could be provided for a required argument | symfony ArgumentValueResolverInterface ArgumentValueResolverInterface =============================== interface **ArgumentValueResolverInterface** Responsible for resolving the value of an argument based on its metadata. Methods ------- | | | | | --- | --- | --- | | bool | [supports](#method_supports)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Whether this resolver can resolve the value for the given ArgumentMetadata. | | | [Generator](http://php.net/Generator) | [resolve](#method_resolve)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Returns the possible value(s). | | Details ------- ### bool supports([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Whether this resolver can resolve the value for the given ArgumentMetadata. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [ArgumentMetadata](../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") | $argument | | #### Return Value | | | | --- | --- | | bool | | ### [Generator](http://php.net/Generator) resolve([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Returns the possible value(s). #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [ArgumentMetadata](../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") | $argument | | #### Return Value | | | | --- | --- | | [Generator](http://php.net/Generator) | | symfony ArgumentResolver ArgumentResolver ================= class **ArgumentResolver** implements [ArgumentResolverInterface](argumentresolverinterface "Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface") Responsible for resolving the arguments passed to an action. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([ArgumentMetadataFactoryInterface](../controllermetadata/argumentmetadatafactoryinterface "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadataFactoryInterface") $argumentMetadataFactory = null, iterable $argumentValueResolvers = array()) | | | array | [getArguments](#method_getArguments)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, callable $controller) Returns the arguments to pass to the controller. | | | static iterable | [getDefaultArgumentValueResolvers](#method_getDefaultArgumentValueResolvers)() | | Details ------- ### \_\_construct([ArgumentMetadataFactoryInterface](../controllermetadata/argumentmetadatafactoryinterface "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadataFactoryInterface") $argumentMetadataFactory = null, iterable $argumentValueResolvers = array()) #### Parameters | | | | | --- | --- | --- | | [ArgumentMetadataFactoryInterface](../controllermetadata/argumentmetadatafactoryinterface "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadataFactoryInterface") | $argumentMetadataFactory | | | iterable | $argumentValueResolvers | | ### array getArguments([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, callable $controller) Returns the arguments to pass to the controller. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | callable | $controller | | #### Return Value | | | | --- | --- | | array | An array of arguments to pass to the controller | #### Exceptions | | | | --- | --- | | [RuntimeException](http://php.net/RuntimeException) | When no value could be provided for a required argument | ### static iterable getDefaultArgumentValueResolvers() #### Return Value | | | | --- | --- | | iterable | | symfony DefaultValueResolver DefaultValueResolver ===================== class **DefaultValueResolver** implements [ArgumentValueResolverInterface](../argumentvalueresolverinterface "Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface") Yields the default value defined in the action signature when no value has been given. Methods ------- | | | | | --- | --- | --- | | bool | [supports](#method_supports)([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Whether this resolver can resolve the value for the given ArgumentMetadata. | | | [Generator](http://php.net/Generator) | [resolve](#method_resolve)([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Returns the possible value(s). | | Details ------- ### bool supports([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Whether this resolver can resolve the value for the given ArgumentMetadata. #### Parameters | | | | | --- | --- | --- | | [Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") | $argument | | #### Return Value | | | | --- | --- | | bool | | ### [Generator](http://php.net/Generator) resolve([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Returns the possible value(s). #### Parameters | | | | | --- | --- | --- | | [Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") | $argument | | #### Return Value | | | | --- | --- | | [Generator](http://php.net/Generator) | | symfony SessionValueResolver SessionValueResolver ===================== class **SessionValueResolver** implements [ArgumentValueResolverInterface](../argumentvalueresolverinterface "Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface") Yields the Session. Methods ------- | | | | | --- | --- | --- | | bool | [supports](#method_supports)([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Whether this resolver can resolve the value for the given ArgumentMetadata. | | | [Generator](http://php.net/Generator) | [resolve](#method_resolve)([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Returns the possible value(s). | | Details ------- ### bool supports([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Whether this resolver can resolve the value for the given ArgumentMetadata. #### Parameters | | | | | --- | --- | --- | | [Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") | $argument | | #### Return Value | | | | --- | --- | | bool | | ### [Generator](http://php.net/Generator) resolve([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Returns the possible value(s). #### Parameters | | | | | --- | --- | --- | | [Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") | $argument | | #### Return Value | | | | --- | --- | | [Generator](http://php.net/Generator) | | symfony TraceableValueResolver TraceableValueResolver ======================= class **TraceableValueResolver** implements [ArgumentValueResolverInterface](../argumentvalueresolverinterface "Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface") Provides timing information via the stopwatch. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([ArgumentValueResolverInterface](../argumentvalueresolverinterface "Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface") $inner, [Stopwatch](../../../stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") $stopwatch) | | | bool | [supports](#method_supports)([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Whether this resolver can resolve the value for the given ArgumentMetadata. | | | [Generator](http://php.net/Generator) | [resolve](#method_resolve)([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Returns the possible value(s). | | Details ------- ### \_\_construct([ArgumentValueResolverInterface](../argumentvalueresolverinterface "Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface") $inner, [Stopwatch](../../../stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") $stopwatch) #### Parameters | | | | | --- | --- | --- | | [ArgumentValueResolverInterface](../argumentvalueresolverinterface "Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface") | $inner | | | [Stopwatch](../../../stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") | $stopwatch | | ### bool supports([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Whether this resolver can resolve the value for the given ArgumentMetadata. #### Parameters | | | | | --- | --- | --- | | [Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") | $argument | | #### Return Value | | | | --- | --- | | bool | | ### [Generator](http://php.net/Generator) resolve([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Returns the possible value(s). #### Parameters | | | | | --- | --- | --- | | [Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") | $argument | | #### Return Value | | | | --- | --- | | [Generator](http://php.net/Generator) | | symfony RequestValueResolver RequestValueResolver ===================== class **RequestValueResolver** implements [ArgumentValueResolverInterface](../argumentvalueresolverinterface "Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface") Yields the same instance as the request object passed along. Methods ------- | | | | | --- | --- | --- | | bool | [supports](#method_supports)([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Whether this resolver can resolve the value for the given ArgumentMetadata. | | | [Generator](http://php.net/Generator) | [resolve](#method_resolve)([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Returns the possible value(s). | | Details ------- ### bool supports([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Whether this resolver can resolve the value for the given ArgumentMetadata. #### Parameters | | | | | --- | --- | --- | | [Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") | $argument | | #### Return Value | | | | --- | --- | | bool | | ### [Generator](http://php.net/Generator) resolve([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Returns the possible value(s). #### Parameters | | | | | --- | --- | --- | | [Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") | $argument | | #### Return Value | | | | --- | --- | | [Generator](http://php.net/Generator) | | symfony VariadicValueResolver VariadicValueResolver ====================== class **VariadicValueResolver** implements [ArgumentValueResolverInterface](../argumentvalueresolverinterface "Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface") Yields a variadic argument's values from the request attributes. Methods ------- | | | | | --- | --- | --- | | bool | [supports](#method_supports)([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Whether this resolver can resolve the value for the given ArgumentMetadata. | | | [Generator](http://php.net/Generator) | [resolve](#method_resolve)([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Returns the possible value(s). | | Details ------- ### bool supports([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Whether this resolver can resolve the value for the given ArgumentMetadata. #### Parameters | | | | | --- | --- | --- | | [Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") | $argument | | #### Return Value | | | | --- | --- | | bool | | ### [Generator](http://php.net/Generator) resolve([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Returns the possible value(s). #### Parameters | | | | | --- | --- | --- | | [Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") | $argument | | #### Return Value | | | | --- | --- | | [Generator](http://php.net/Generator) | |
programming_docs
symfony RequestAttributeValueResolver RequestAttributeValueResolver ============================== class **RequestAttributeValueResolver** implements [ArgumentValueResolverInterface](../argumentvalueresolverinterface "Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface") Yields a non-variadic argument's value from the request attributes. Methods ------- | | | | | --- | --- | --- | | bool | [supports](#method_supports)([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Whether this resolver can resolve the value for the given ArgumentMetadata. | | | [Generator](http://php.net/Generator) | [resolve](#method_resolve)([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Returns the possible value(s). | | Details ------- ### bool supports([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Whether this resolver can resolve the value for the given ArgumentMetadata. #### Parameters | | | | | --- | --- | --- | | [Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") | $argument | | #### Return Value | | | | --- | --- | | bool | | ### [Generator](http://php.net/Generator) resolve([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Returns the possible value(s). #### Parameters | | | | | --- | --- | --- | | [Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") | $argument | | #### Return Value | | | | --- | --- | | [Generator](http://php.net/Generator) | | symfony ServiceValueResolver ServiceValueResolver ===================== class **ServiceValueResolver** implements [ArgumentValueResolverInterface](../argumentvalueresolverinterface "Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface") Yields a service keyed by \_controller and argument name. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(ContainerInterface $container) | | | bool | [supports](#method_supports)([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Whether this resolver can resolve the value for the given ArgumentMetadata. | | | [Generator](http://php.net/Generator) | [resolve](#method_resolve)([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Returns the possible value(s). | | Details ------- ### \_\_construct(ContainerInterface $container) #### Parameters | | | | | --- | --- | --- | | ContainerInterface | $container | | ### bool supports([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Whether this resolver can resolve the value for the given ArgumentMetadata. #### Parameters | | | | | --- | --- | --- | | [Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") | $argument | | #### Return Value | | | | --- | --- | | bool | | ### [Generator](http://php.net/Generator) resolve([Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") $argument) Returns the possible value(s). #### Parameters | | | | | --- | --- | --- | | [Request](../../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [ArgumentMetadata](../../controllermetadata/argumentmetadata "Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata") | $argument | | #### Return Value | | | | --- | --- | | [Generator](http://php.net/Generator) | | symfony FragmentHandler FragmentHandler ================ class **FragmentHandler** Renders a URI that represents a resource fragment. This class handles the rendering of resource fragments that are included into a main resource. The handling of the rendering is managed by specialized renderers. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack, array $renderers = array(), bool $debug = false) | | | | [addRenderer](#method_addRenderer)([FragmentRendererInterface](fragmentrendererinterface "Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface") $renderer) Adds a renderer. | | | string|null | [render](#method_render)(string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $uri, string $renderer = 'inline', array $options = array()) Renders a URI and returns the Response content. | | | string|null | [deliver](#method_deliver)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Delivers the Response as a string. | | Details ------- ### \_\_construct([RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack, array $renderers = array(), bool $debug = false) #### Parameters | | | | | --- | --- | --- | | [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") | $requestStack | The Request stack that controls the lifecycle of requests | | array | $renderers | An array of FragmentRendererInterface instances | | bool | $debug | Whether the debug mode is enabled or not | ### addRenderer([FragmentRendererInterface](fragmentrendererinterface "Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface") $renderer) Adds a renderer. #### Parameters | | | | | --- | --- | --- | | [FragmentRendererInterface](fragmentrendererinterface "Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface") | $renderer | | ### string|null render(string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $uri, string $renderer = 'inline', array $options = array()) Renders a URI and returns the Response content. Available options: * ignore\_errors: true to return an empty string in case of an error #### Parameters | | | | | --- | --- | --- | | string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") | $uri | A URI as a string or a ControllerReference instance | | string | $renderer | The renderer name | | array | $options | An array of options | #### Return Value | | | | --- | --- | | string|null | The Response content or null when the Response is streamed | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](http://php.net/InvalidArgumentException) | when the renderer does not exist | | [LogicException](http://php.net/LogicException) | when no master request is being handled | ### protected string|null deliver([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Delivers the Response as a string. When the Response is a StreamedResponse, the content is streamed immediately instead of being returned. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | #### Return Value | | | | --- | --- | | string|null | The Response content or null when the Response is streamed | #### Exceptions | | | | --- | --- | | [RuntimeException](http://php.net/RuntimeException) | when the Response is not successful | symfony HIncludeFragmentRenderer HIncludeFragmentRenderer ========================= class **HIncludeFragmentRenderer** extends [RoutableFragmentRenderer](routablefragmentrenderer "Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer") Implements the Hinclude rendering strategy. Methods ------- | | | | | --- | --- | --- | | | [setFragmentPath](#method_setFragmentPath)(string $path) Sets the fragment path that triggers the fragment listener. | from [RoutableFragmentRenderer](routablefragmentrenderer#method_setFragmentPath "Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer") | | string | [generateFragmentUri](#method_generateFragmentUri)([ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $reference, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $absolute = false, bool $strict = true) Generates a fragment URI for a given controller. | from [RoutableFragmentRenderer](routablefragmentrenderer#method_generateFragmentUri "Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer") | | | [\_\_construct](#method___construct)([EngineInterface](../../templating/engineinterface "Symfony\Component\Templating\EngineInterface")|Environment $templating = null, [UriSigner](../urisigner "Symfony\Component\HttpKernel\UriSigner") $signer = null, string $globalDefaultTemplate = null, string $charset = 'utf-8') | | | | [setTemplating](#method_setTemplating)([EngineInterface](../../templating/engineinterface "Symfony\Component\Templating\EngineInterface")|Environment|null $templating) Sets the templating engine to use to render the default content. | | | bool | [hasTemplating](#method_hasTemplating)() Checks if a templating engine has been set. | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [render](#method_render)(string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $uri, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, array $options = array()) Renders a URI and returns the Response content. | | | string | [getName](#method_getName)() Gets the name of the strategy. | | Details ------- ### setFragmentPath(string $path) Sets the fragment path that triggers the fragment listener. #### Parameters | | | | | --- | --- | --- | | string | $path | The path | #### See also | | | | --- | --- | | [FragmentListener](../eventlistener/fragmentlistener "Symfony\Component\HttpKernel\EventListener\FragmentListener") | | ### protected string generateFragmentUri([ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $reference, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $absolute = false, bool $strict = true) Generates a fragment URI for a given controller. #### Parameters | | | | | --- | --- | --- | | [ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") | $reference | A ControllerReference instance | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | bool | $absolute | Whether to generate an absolute URL or not | | bool | $strict | Whether to allow non-scalar attributes or not | #### Return Value | | | | --- | --- | | string | A fragment URI | ### \_\_construct([EngineInterface](../../templating/engineinterface "Symfony\Component\Templating\EngineInterface")|Environment $templating = null, [UriSigner](../urisigner "Symfony\Component\HttpKernel\UriSigner") $signer = null, string $globalDefaultTemplate = null, string $charset = 'utf-8') #### Parameters | | | | | --- | --- | --- | | [EngineInterface](../../templating/engineinterface "Symfony\Component\Templating\EngineInterface")|Environment | $templating | An EngineInterface or a Twig instance | | [UriSigner](../urisigner "Symfony\Component\HttpKernel\UriSigner") | $signer | A UriSigner instance | | string | $globalDefaultTemplate | The global default content (it can be a template name or the content) | | string | $charset | | ### setTemplating([EngineInterface](../../templating/engineinterface "Symfony\Component\Templating\EngineInterface")|Environment|null $templating) Sets the templating engine to use to render the default content. #### Parameters | | | | | --- | --- | --- | | [EngineInterface](../../templating/engineinterface "Symfony\Component\Templating\EngineInterface")|Environment|null | $templating | An EngineInterface or an Environment instance | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](http://php.net/InvalidArgumentException) | | ### bool hasTemplating() Checks if a templating engine has been set. #### Return Value | | | | --- | --- | | bool | true if the templating engine has been set, false otherwise | ### [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") render(string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $uri, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, array $options = array()) Renders a URI and returns the Response content. #### Parameters | | | | | --- | --- | --- | | string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") | $uri | A URI as a string or a ControllerReference instance | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | array | $options | An array of options | #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | A Response instance | ### string getName() Gets the name of the strategy. #### Return Value | | | | --- | --- | | string | The strategy name | symfony RoutableFragmentRenderer RoutableFragmentRenderer ========================= abstract class **RoutableFragmentRenderer** implements [FragmentRendererInterface](fragmentrendererinterface "Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface") Adds the possibility to generate a fragment URI for a given Controller. Methods ------- | | | | | --- | --- | --- | | | [setFragmentPath](#method_setFragmentPath)(string $path) Sets the fragment path that triggers the fragment listener. | | | string | [generateFragmentUri](#method_generateFragmentUri)([ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $reference, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $absolute = false, bool $strict = true) Generates a fragment URI for a given controller. | | Details ------- ### setFragmentPath(string $path) Sets the fragment path that triggers the fragment listener. #### Parameters | | | | | --- | --- | --- | | string | $path | The path | #### See also | | | | --- | --- | | [FragmentListener](../eventlistener/fragmentlistener "Symfony\Component\HttpKernel\EventListener\FragmentListener") | | ### protected string generateFragmentUri([ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $reference, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $absolute = false, bool $strict = true) Generates a fragment URI for a given controller. #### Parameters | | | | | --- | --- | --- | | [ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") | $reference | A ControllerReference instance | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | bool | $absolute | Whether to generate an absolute URL or not | | bool | $strict | Whether to allow non-scalar attributes or not | #### Return Value | | | | --- | --- | | string | A fragment URI | symfony SsiFragmentRenderer SsiFragmentRenderer ==================== class **SsiFragmentRenderer** extends [AbstractSurrogateFragmentRenderer](abstractsurrogatefragmentrenderer "Symfony\Component\HttpKernel\Fragment\AbstractSurrogateFragmentRenderer") Implements the SSI rendering strategy. Methods ------- | | | | | --- | --- | --- | | | [setFragmentPath](#method_setFragmentPath)(string $path) Sets the fragment path that triggers the fragment listener. | from [RoutableFragmentRenderer](routablefragmentrenderer#method_setFragmentPath "Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer") | | string | [generateFragmentUri](#method_generateFragmentUri)([ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $reference, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $absolute = false, bool $strict = true) Generates a fragment URI for a given controller. | from [RoutableFragmentRenderer](routablefragmentrenderer#method_generateFragmentUri "Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer") | | | [\_\_construct](#method___construct)([SurrogateInterface](../httpcache/surrogateinterface "Symfony\Component\HttpKernel\HttpCache\SurrogateInterface") $surrogate = null, [FragmentRendererInterface](fragmentrendererinterface "Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface") $inlineStrategy, [UriSigner](../urisigner "Symfony\Component\HttpKernel\UriSigner") $signer = null) The "fallback" strategy when surrogate is not available should always be an instance of InlineFragmentRenderer. | from [AbstractSurrogateFragmentRenderer](abstractsurrogatefragmentrenderer#method___construct "Symfony\Component\HttpKernel\Fragment\AbstractSurrogateFragmentRenderer") | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [render](#method_render)(string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $uri, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, array $options = array()) Renders a URI and returns the Response content. | from [AbstractSurrogateFragmentRenderer](abstractsurrogatefragmentrenderer#method_render "Symfony\Component\HttpKernel\Fragment\AbstractSurrogateFragmentRenderer") | | string | [getName](#method_getName)() Gets the name of the strategy. | | Details ------- ### setFragmentPath(string $path) Sets the fragment path that triggers the fragment listener. #### Parameters | | | | | --- | --- | --- | | string | $path | The path | #### See also | | | | --- | --- | | [FragmentListener](../eventlistener/fragmentlistener "Symfony\Component\HttpKernel\EventListener\FragmentListener") | | ### protected string generateFragmentUri([ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $reference, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $absolute = false, bool $strict = true) Generates a fragment URI for a given controller. #### Parameters | | | | | --- | --- | --- | | [ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") | $reference | A ControllerReference instance | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | bool | $absolute | Whether to generate an absolute URL or not | | bool | $strict | Whether to allow non-scalar attributes or not | #### Return Value | | | | --- | --- | | string | A fragment URI | ### \_\_construct([SurrogateInterface](../httpcache/surrogateinterface "Symfony\Component\HttpKernel\HttpCache\SurrogateInterface") $surrogate = null, [FragmentRendererInterface](fragmentrendererinterface "Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface") $inlineStrategy, [UriSigner](../urisigner "Symfony\Component\HttpKernel\UriSigner") $signer = null) The "fallback" strategy when surrogate is not available should always be an instance of InlineFragmentRenderer. #### Parameters | | | | | --- | --- | --- | | [SurrogateInterface](../httpcache/surrogateinterface "Symfony\Component\HttpKernel\HttpCache\SurrogateInterface") | $surrogate | An Surrogate instance | | [FragmentRendererInterface](fragmentrendererinterface "Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface") | $inlineStrategy | The inline strategy to use when the surrogate is not supported | | [UriSigner](../urisigner "Symfony\Component\HttpKernel\UriSigner") | $signer | | ### [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") render(string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $uri, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, array $options = array()) Renders a URI and returns the Response content. #### Parameters | | | | | --- | --- | --- | | string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") | $uri | A URI as a string or a ControllerReference instance | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | array | $options | An array of options | #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | A Response instance | #### See also | | | | --- | --- | | SurrogateInterface | | ### string getName() Gets the name of the strategy. #### Return Value | | | | --- | --- | | string | The strategy name |
programming_docs
symfony AbstractSurrogateFragmentRenderer AbstractSurrogateFragmentRenderer ================================== abstract class **AbstractSurrogateFragmentRenderer** extends [RoutableFragmentRenderer](routablefragmentrenderer "Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer") Implements Surrogate rendering strategy. Methods ------- | | | | | --- | --- | --- | | | [setFragmentPath](#method_setFragmentPath)(string $path) Sets the fragment path that triggers the fragment listener. | from [RoutableFragmentRenderer](routablefragmentrenderer#method_setFragmentPath "Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer") | | string | [generateFragmentUri](#method_generateFragmentUri)([ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $reference, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $absolute = false, bool $strict = true) Generates a fragment URI for a given controller. | from [RoutableFragmentRenderer](routablefragmentrenderer#method_generateFragmentUri "Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer") | | | [\_\_construct](#method___construct)([SurrogateInterface](../httpcache/surrogateinterface "Symfony\Component\HttpKernel\HttpCache\SurrogateInterface") $surrogate = null, [FragmentRendererInterface](fragmentrendererinterface "Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface") $inlineStrategy, [UriSigner](../urisigner "Symfony\Component\HttpKernel\UriSigner") $signer = null) The "fallback" strategy when surrogate is not available should always be an instance of InlineFragmentRenderer. | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [render](#method_render)(string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $uri, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, array $options = array()) Renders a URI and returns the Response content. | | Details ------- ### setFragmentPath(string $path) Sets the fragment path that triggers the fragment listener. #### Parameters | | | | | --- | --- | --- | | string | $path | The path | #### See also | | | | --- | --- | | [FragmentListener](../eventlistener/fragmentlistener "Symfony\Component\HttpKernel\EventListener\FragmentListener") | | ### protected string generateFragmentUri([ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $reference, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $absolute = false, bool $strict = true) Generates a fragment URI for a given controller. #### Parameters | | | | | --- | --- | --- | | [ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") | $reference | A ControllerReference instance | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | bool | $absolute | Whether to generate an absolute URL or not | | bool | $strict | Whether to allow non-scalar attributes or not | #### Return Value | | | | --- | --- | | string | A fragment URI | ### \_\_construct([SurrogateInterface](../httpcache/surrogateinterface "Symfony\Component\HttpKernel\HttpCache\SurrogateInterface") $surrogate = null, [FragmentRendererInterface](fragmentrendererinterface "Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface") $inlineStrategy, [UriSigner](../urisigner "Symfony\Component\HttpKernel\UriSigner") $signer = null) The "fallback" strategy when surrogate is not available should always be an instance of InlineFragmentRenderer. #### Parameters | | | | | --- | --- | --- | | [SurrogateInterface](../httpcache/surrogateinterface "Symfony\Component\HttpKernel\HttpCache\SurrogateInterface") | $surrogate | An Surrogate instance | | [FragmentRendererInterface](fragmentrendererinterface "Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface") | $inlineStrategy | The inline strategy to use when the surrogate is not supported | | [UriSigner](../urisigner "Symfony\Component\HttpKernel\UriSigner") | $signer | | ### [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") render(string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $uri, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, array $options = array()) Renders a URI and returns the Response content. #### Parameters | | | | | --- | --- | --- | | string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") | $uri | A URI as a string or a ControllerReference instance | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | array | $options | An array of options | #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | A Response instance | #### See also | | | | --- | --- | | SurrogateInterface | | symfony EsiFragmentRenderer EsiFragmentRenderer ==================== class **EsiFragmentRenderer** extends [AbstractSurrogateFragmentRenderer](abstractsurrogatefragmentrenderer "Symfony\Component\HttpKernel\Fragment\AbstractSurrogateFragmentRenderer") Implements the ESI rendering strategy. Methods ------- | | | | | --- | --- | --- | | | [setFragmentPath](#method_setFragmentPath)(string $path) Sets the fragment path that triggers the fragment listener. | from [RoutableFragmentRenderer](routablefragmentrenderer#method_setFragmentPath "Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer") | | string | [generateFragmentUri](#method_generateFragmentUri)([ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $reference, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $absolute = false, bool $strict = true) Generates a fragment URI for a given controller. | from [RoutableFragmentRenderer](routablefragmentrenderer#method_generateFragmentUri "Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer") | | | [\_\_construct](#method___construct)([SurrogateInterface](../httpcache/surrogateinterface "Symfony\Component\HttpKernel\HttpCache\SurrogateInterface") $surrogate = null, [FragmentRendererInterface](fragmentrendererinterface "Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface") $inlineStrategy, [UriSigner](../urisigner "Symfony\Component\HttpKernel\UriSigner") $signer = null) The "fallback" strategy when surrogate is not available should always be an instance of InlineFragmentRenderer. | from [AbstractSurrogateFragmentRenderer](abstractsurrogatefragmentrenderer#method___construct "Symfony\Component\HttpKernel\Fragment\AbstractSurrogateFragmentRenderer") | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [render](#method_render)(string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $uri, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, array $options = array()) Renders a URI and returns the Response content. | from [AbstractSurrogateFragmentRenderer](abstractsurrogatefragmentrenderer#method_render "Symfony\Component\HttpKernel\Fragment\AbstractSurrogateFragmentRenderer") | | string | [getName](#method_getName)() Gets the name of the strategy. | | Details ------- ### setFragmentPath(string $path) Sets the fragment path that triggers the fragment listener. #### Parameters | | | | | --- | --- | --- | | string | $path | The path | #### See also | | | | --- | --- | | [FragmentListener](../eventlistener/fragmentlistener "Symfony\Component\HttpKernel\EventListener\FragmentListener") | | ### protected string generateFragmentUri([ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $reference, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $absolute = false, bool $strict = true) Generates a fragment URI for a given controller. #### Parameters | | | | | --- | --- | --- | | [ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") | $reference | A ControllerReference instance | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | bool | $absolute | Whether to generate an absolute URL or not | | bool | $strict | Whether to allow non-scalar attributes or not | #### Return Value | | | | --- | --- | | string | A fragment URI | ### \_\_construct([SurrogateInterface](../httpcache/surrogateinterface "Symfony\Component\HttpKernel\HttpCache\SurrogateInterface") $surrogate = null, [FragmentRendererInterface](fragmentrendererinterface "Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface") $inlineStrategy, [UriSigner](../urisigner "Symfony\Component\HttpKernel\UriSigner") $signer = null) The "fallback" strategy when surrogate is not available should always be an instance of InlineFragmentRenderer. #### Parameters | | | | | --- | --- | --- | | [SurrogateInterface](../httpcache/surrogateinterface "Symfony\Component\HttpKernel\HttpCache\SurrogateInterface") | $surrogate | An Surrogate instance | | [FragmentRendererInterface](fragmentrendererinterface "Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface") | $inlineStrategy | The inline strategy to use when the surrogate is not supported | | [UriSigner](../urisigner "Symfony\Component\HttpKernel\UriSigner") | $signer | | ### [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") render(string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $uri, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, array $options = array()) Renders a URI and returns the Response content. #### Parameters | | | | | --- | --- | --- | | string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") | $uri | A URI as a string or a ControllerReference instance | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | array | $options | An array of options | #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | A Response instance | #### See also | | | | --- | --- | | SurrogateInterface | | ### string getName() Gets the name of the strategy. #### Return Value | | | | --- | --- | | string | The strategy name | symfony FragmentRendererInterface FragmentRendererInterface ========================== interface **FragmentRendererInterface** Interface implemented by all rendering strategies. Methods ------- | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [render](#method_render)(string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $uri, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, array $options = array()) Renders a URI and returns the Response content. | | | string | [getName](#method_getName)() Gets the name of the strategy. | | Details ------- ### [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") render(string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $uri, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, array $options = array()) Renders a URI and returns the Response content. #### Parameters | | | | | --- | --- | --- | | string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") | $uri | A URI as a string or a ControllerReference instance | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | array | $options | An array of options | #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | A Response instance | ### string getName() Gets the name of the strategy. #### Return Value | | | | --- | --- | | string | The strategy name | symfony InlineFragmentRenderer InlineFragmentRenderer ======================= class **InlineFragmentRenderer** extends [RoutableFragmentRenderer](routablefragmentrenderer "Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer") Implements the inline rendering strategy where the Request is rendered by the current HTTP kernel. Methods ------- | | | | | --- | --- | --- | | | [setFragmentPath](#method_setFragmentPath)(string $path) Sets the fragment path that triggers the fragment listener. | from [RoutableFragmentRenderer](routablefragmentrenderer#method_setFragmentPath "Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer") | | string | [generateFragmentUri](#method_generateFragmentUri)([ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $reference, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $absolute = false, bool $strict = true) Generates a fragment URI for a given controller. | from [RoutableFragmentRenderer](routablefragmentrenderer#method_generateFragmentUri "Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer") | | | [\_\_construct](#method___construct)([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, [EventDispatcherInterface](../../eventdispatcher/eventdispatcherinterface "Symfony\Component\EventDispatcher\EventDispatcherInterface") $dispatcher = null) | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [render](#method_render)(string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $uri, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, array $options = array()) Renders a URI and returns the Response content. | | | | [createSubRequest](#method_createSubRequest)($uri, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) | | | string | [getName](#method_getName)() Gets the name of the strategy. | | Details ------- ### setFragmentPath(string $path) Sets the fragment path that triggers the fragment listener. #### Parameters | | | | | --- | --- | --- | | string | $path | The path | #### See also | | | | --- | --- | | [FragmentListener](../eventlistener/fragmentlistener "Symfony\Component\HttpKernel\EventListener\FragmentListener") | | ### protected string generateFragmentUri([ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $reference, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $absolute = false, bool $strict = true) Generates a fragment URI for a given controller. #### Parameters | | | | | --- | --- | --- | | [ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") | $reference | A ControllerReference instance | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | bool | $absolute | Whether to generate an absolute URL or not | | bool | $strict | Whether to allow non-scalar attributes or not | #### Return Value | | | | --- | --- | | string | A fragment URI | ### \_\_construct([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, [EventDispatcherInterface](../../eventdispatcher/eventdispatcherinterface "Symfony\Component\EventDispatcher\EventDispatcherInterface") $dispatcher = null) #### Parameters | | | | | --- | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | $kernel | | | [EventDispatcherInterface](../../eventdispatcher/eventdispatcherinterface "Symfony\Component\EventDispatcher\EventDispatcherInterface") | $dispatcher | | ### [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") render(string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $uri, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, array $options = array()) Renders a URI and returns the Response content. #### Parameters | | | | | --- | --- | --- | | string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") | $uri | A URI as a string or a ControllerReference instance | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | array | $options | An array of options | #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | A Response instance | ### protected createSubRequest($uri, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) #### Parameters | | | | | --- | --- | --- | | | $uri | | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | ### string getName() Gets the name of the strategy. #### Return Value | | | | --- | --- | | string | The strategy name | symfony StoreInterface StoreInterface =============== interface **StoreInterface** Interface implemented by HTTP cache stores. Methods ------- | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response")|null | [lookup](#method_lookup)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Locates a cached Response for the Request provided. | | | string | [write](#method_write)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Writes a cache entry to the store for the given Request and Response. | | | | [invalidate](#method_invalidate)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Invalidates all cache entries that match the request. | | | bool|string | [lock](#method_lock)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Locks the cache for a given Request. | | | bool | [unlock](#method_unlock)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Releases the lock for the given Request. | | | bool | [isLocked](#method_isLocked)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Returns whether or not a lock exists. | | | bool | [purge](#method_purge)(string $url) Purges data for the given URL. | | | | [cleanup](#method_cleanup)() Cleanups storage. | | Details ------- ### [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response")|null lookup([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Locates a cached Response for the Request provided. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response")|null | A Response instance, or null if no cache entry was found | ### string write([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Writes a cache entry to the store for the given Request and Response. Existing entries are read and any that match the response are removed. This method calls write with the new list of cache entries. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | #### Return Value | | | | --- | --- | | string | The key under which the response is stored | ### invalidate([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Invalidates all cache entries that match the request. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | ### bool|string lock([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Locks the cache for a given Request. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | #### Return Value | | | | --- | --- | | bool|string | true if the lock is acquired, the path to the current lock otherwise | ### bool unlock([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Releases the lock for the given Request. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | #### Return Value | | | | --- | --- | | bool | False if the lock file does not exist or cannot be unlocked, true otherwise | ### bool isLocked([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Returns whether or not a lock exists. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | #### Return Value | | | | --- | --- | | bool | true if lock exists, false otherwise | ### bool purge(string $url) Purges data for the given URL. #### Parameters | | | | | --- | --- | --- | | string | $url | A URL | #### Return Value | | | | --- | --- | | bool | true if the URL exists and has been purged, false otherwise | ### cleanup() Cleanups storage.
programming_docs
symfony ResponseCacheStrategyInterface ResponseCacheStrategyInterface =============================== interface **ResponseCacheStrategyInterface** ResponseCacheStrategyInterface implementations know how to compute the Response cache HTTP header based on the different response cache headers. Methods ------- | | | | | --- | --- | --- | | | [add](#method_add)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Adds a Response. | | | | [update](#method_update)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Updates the Response HTTP headers based on the embedded Responses. | | Details ------- ### add([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Adds a Response. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | ### update([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Updates the Response HTTP headers based on the embedded Responses. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | symfony SubRequestHandler SubRequestHandler ================== class **SubRequestHandler** Methods ------- | | | | | --- | --- | --- | | static [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [handle](#method_handle)([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, $type, $catch) | | Details ------- ### static [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") handle([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, $type, $catch) #### Parameters | | | | | --- | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | $kernel | | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | | $type | | | | $catch | | #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | | symfony ResponseCacheStrategy ResponseCacheStrategy ====================== class **ResponseCacheStrategy** implements [ResponseCacheStrategyInterface](responsecachestrategyinterface "Symfony\Component\HttpKernel\HttpCache\ResponseCacheStrategyInterface") ResponseCacheStrategy knows how to compute the Response cache HTTP header based on the different response cache headers. This implementation changes the master response TTL to the smallest TTL received or force validation if one of the surrogates has validation cache strategy. Methods ------- | | | | | --- | --- | --- | | | [add](#method_add)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Adds a Response. | | | | [update](#method_update)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Updates the Response HTTP headers based on the embedded Responses. | | Details ------- ### add([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Adds a Response. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | ### update([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Updates the Response HTTP headers based on the embedded Responses. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | symfony Ssi Ssi ==== class **Ssi** extends [AbstractSurrogate](abstractsurrogate "Symfony\Component\HttpKernel\HttpCache\AbstractSurrogate") Ssi implements the SSI capabilities to Request and Response instances. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $contentTypes | | from [AbstractSurrogate](abstractsurrogate#property_contentTypes "Symfony\Component\HttpKernel\HttpCache\AbstractSurrogate") | | protected | $phpEscapeMap | | from [AbstractSurrogate](abstractsurrogate#property_phpEscapeMap "Symfony\Component\HttpKernel\HttpCache\AbstractSurrogate") | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(array $contentTypes = array('text/html', 'text/xml', 'application/xhtml+xml', 'application/xml')) | from [AbstractSurrogate](abstractsurrogate#method___construct "Symfony\Component\HttpKernel\HttpCache\AbstractSurrogate") | | [ResponseCacheStrategyInterface](responsecachestrategyinterface "Symfony\Component\HttpKernel\HttpCache\ResponseCacheStrategyInterface") | [createCacheStrategy](#method_createCacheStrategy)() Returns a new cache strategy instance. | from [AbstractSurrogate](abstractsurrogate#method_createCacheStrategy "Symfony\Component\HttpKernel\HttpCache\AbstractSurrogate") | | bool | [hasSurrogateCapability](#method_hasSurrogateCapability)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Checks that at least one surrogate has Surrogate capability. | from [AbstractSurrogate](abstractsurrogate#method_hasSurrogateCapability "Symfony\Component\HttpKernel\HttpCache\AbstractSurrogate") | | | [addSurrogateCapability](#method_addSurrogateCapability)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Adds Surrogate-capability to the given Request. | from [AbstractSurrogate](abstractsurrogate#method_addSurrogateCapability "Symfony\Component\HttpKernel\HttpCache\AbstractSurrogate") | | bool | [needsParsing](#method_needsParsing)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Checks that the Response needs to be parsed for Surrogate tags. | from [AbstractSurrogate](abstractsurrogate#method_needsParsing "Symfony\Component\HttpKernel\HttpCache\AbstractSurrogate") | | string | [handle](#method_handle)([HttpCache](httpcache "Symfony\Component\HttpKernel\HttpCache\HttpCache") $cache, string $uri, string $alt, bool $ignoreErrors) Handles a Surrogate from the cache. | from [AbstractSurrogate](abstractsurrogate#method_handle "Symfony\Component\HttpKernel\HttpCache\AbstractSurrogate") | | | [removeFromControl](#method_removeFromControl)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Remove the Surrogate from the Surrogate-Control header. | from [AbstractSurrogate](abstractsurrogate#method_removeFromControl "Symfony\Component\HttpKernel\HttpCache\AbstractSurrogate") | | string | [getName](#method_getName)() Returns surrogate name. | | | | [addSurrogateControl](#method_addSurrogateControl)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Adds HTTP headers to specify that the Response needs to be parsed for Surrogate. | | | string | [renderIncludeTag](#method_renderIncludeTag)(string $uri, string $alt = null, bool $ignoreErrors = true, string $comment = '') Renders a Surrogate tag. | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [process](#method_process)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Replaces a Response Surrogate tags with the included resource content. | | Details ------- ### \_\_construct(array $contentTypes = array('text/html', 'text/xml', 'application/xhtml+xml', 'application/xml')) #### Parameters | | | | | --- | --- | --- | | array | $contentTypes | An array of content-type that should be parsed for Surrogate information (default: text/html, text/xml, application/xhtml+xml, and application/xml) | ### [ResponseCacheStrategyInterface](responsecachestrategyinterface "Symfony\Component\HttpKernel\HttpCache\ResponseCacheStrategyInterface") createCacheStrategy() Returns a new cache strategy instance. #### Return Value | | | | --- | --- | | [ResponseCacheStrategyInterface](responsecachestrategyinterface "Symfony\Component\HttpKernel\HttpCache\ResponseCacheStrategyInterface") | A ResponseCacheStrategyInterface instance | ### bool hasSurrogateCapability([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Checks that at least one surrogate has Surrogate capability. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | #### Return Value | | | | --- | --- | | bool | true if one surrogate has Surrogate capability, false otherwise | ### addSurrogateCapability([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Adds Surrogate-capability to the given Request. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | ### bool needsParsing([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Checks that the Response needs to be parsed for Surrogate tags. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | #### Return Value | | | | --- | --- | | bool | true if the Response needs to be parsed, false otherwise | ### string handle([HttpCache](httpcache "Symfony\Component\HttpKernel\HttpCache\HttpCache") $cache, string $uri, string $alt, bool $ignoreErrors) Handles a Surrogate from the cache. #### Parameters | | | | | --- | --- | --- | | [HttpCache](httpcache "Symfony\Component\HttpKernel\HttpCache\HttpCache") | $cache | An HttpCache instance | | string | $uri | The main URI | | string | $alt | An alternative URI | | bool | $ignoreErrors | Whether to ignore errors or not | #### Return Value | | | | --- | --- | | string | | #### Exceptions | | | | --- | --- | | [RuntimeException](http://php.net/RuntimeException) | | | [Exception](http://php.net/Exception) | | ### protected removeFromControl([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Remove the Surrogate from the Surrogate-Control header. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | ### string getName() Returns surrogate name. #### Return Value | | | | --- | --- | | string | | ### addSurrogateControl([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Adds HTTP headers to specify that the Response needs to be parsed for Surrogate. This method only adds an Surrogate HTTP header if the Response has some Surrogate tags. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | ### string renderIncludeTag(string $uri, string $alt = null, bool $ignoreErrors = true, string $comment = '') Renders a Surrogate tag. #### Parameters | | | | | --- | --- | --- | | string | $uri | A URI | | string | $alt | An alternate URI | | bool | $ignoreErrors | Whether to ignore errors or not | | string | $comment | A comment to add as an esi:include tag | #### Return Value | | | | --- | --- | | string | | ### [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") process([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Replaces a Response Surrogate tags with the included resource content. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | | symfony Store Store ====== class **Store** implements [StoreInterface](storeinterface "Symfony\Component\HttpKernel\HttpCache\StoreInterface") Store implements all the logic for storing cache metadata (Request and Response headers). Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $root | | | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $root) | | | | [cleanup](#method_cleanup)() Cleanups storage. | | | bool|string | [lock](#method_lock)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Tries to lock the cache for a given Request, without blocking. | | | bool | [unlock](#method_unlock)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Releases the lock for the given Request. | | | bool | [isLocked](#method_isLocked)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Returns whether or not a lock exists. | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response")|null | [lookup](#method_lookup)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Locates a cached Response for the Request provided. | | | string | [write](#method_write)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Writes a cache entry to the store for the given Request and Response. | | | string | [generateContentDigest](#method_generateContentDigest)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Returns content digest for $response. | | | | [invalidate](#method_invalidate)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Invalidates all cache entries that match the request. | | | bool | [purge](#method_purge)(string $url) Purges data for the given URL. | | | | [getPath](#method_getPath)($key) | | | string | [generateCacheKey](#method_generateCacheKey)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Generates a cache key for the given Request. | | Details ------- ### \_\_construct(string $root) #### Parameters | | | | | --- | --- | --- | | string | $root | | #### Exceptions | | | | --- | --- | | [RuntimeException](http://php.net/RuntimeException) | | ### cleanup() Cleanups storage. ### bool|string lock([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Tries to lock the cache for a given Request, without blocking. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | #### Return Value | | | | --- | --- | | bool|string | true if the lock is acquired, the path to the current lock otherwise | ### bool unlock([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Releases the lock for the given Request. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | #### Return Value | | | | --- | --- | | bool | False if the lock file does not exist or cannot be unlocked, true otherwise | ### bool isLocked([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Returns whether or not a lock exists. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | #### Return Value | | | | --- | --- | | bool | true if lock exists, false otherwise | ### [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response")|null lookup([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Locates a cached Response for the Request provided. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response")|null | A Response instance, or null if no cache entry was found | ### string write([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Writes a cache entry to the store for the given Request and Response. Existing entries are read and any that match the response are removed. This method calls write with the new list of cache entries. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | #### Return Value | | | | --- | --- | | string | The key under which the response is stored | #### Exceptions | | | | --- | --- | | [RuntimeException](http://php.net/RuntimeException) | | ### protected string generateContentDigest([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Returns content digest for $response. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | #### Return Value | | | | --- | --- | | string | | ### invalidate([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Invalidates all cache entries that match the request. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | #### Exceptions | | | | --- | --- | | [RuntimeException](http://php.net/RuntimeException) | | ### bool purge(string $url) Purges data for the given URL. This method purges both the HTTP and the HTTPS version of the cache entry. #### Parameters | | | | | --- | --- | --- | | string | $url | A URL | #### Return Value | | | | --- | --- | | bool | true if the URL exists and has been purged, false otherwise | ### getPath($key) #### Parameters | | | | | --- | --- | --- | | | $key | | ### protected string generateCacheKey([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Generates a cache key for the given Request. This method should return a key that must only depend on a normalized version of the request URI. If the same URI can have more than one representation, based on some headers, use a Vary header to indicate them, and each representation will be stored independently under the same cache key. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | #### Return Value | | | | --- | --- | | string | A key for the given Request |
programming_docs
symfony AbstractSurrogate AbstractSurrogate ================== abstract class **AbstractSurrogate** implements [SurrogateInterface](surrogateinterface "Symfony\Component\HttpKernel\HttpCache\SurrogateInterface") Abstract class implementing Surrogate capabilities to Request and Response instances. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $contentTypes | | | | protected | $phpEscapeMap | | | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(array $contentTypes = array('text/html', 'text/xml', 'application/xhtml+xml', 'application/xml')) | | | [ResponseCacheStrategyInterface](responsecachestrategyinterface "Symfony\Component\HttpKernel\HttpCache\ResponseCacheStrategyInterface") | [createCacheStrategy](#method_createCacheStrategy)() Returns a new cache strategy instance. | | | bool | [hasSurrogateCapability](#method_hasSurrogateCapability)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Checks that at least one surrogate has Surrogate capability. | | | | [addSurrogateCapability](#method_addSurrogateCapability)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Adds Surrogate-capability to the given Request. | | | bool | [needsParsing](#method_needsParsing)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Checks that the Response needs to be parsed for Surrogate tags. | | | string | [handle](#method_handle)([HttpCache](httpcache "Symfony\Component\HttpKernel\HttpCache\HttpCache") $cache, string $uri, string $alt, bool $ignoreErrors) Handles a Surrogate from the cache. | | | | [removeFromControl](#method_removeFromControl)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Remove the Surrogate from the Surrogate-Control header. | | Details ------- ### \_\_construct(array $contentTypes = array('text/html', 'text/xml', 'application/xhtml+xml', 'application/xml')) #### Parameters | | | | | --- | --- | --- | | array | $contentTypes | An array of content-type that should be parsed for Surrogate information (default: text/html, text/xml, application/xhtml+xml, and application/xml) | ### [ResponseCacheStrategyInterface](responsecachestrategyinterface "Symfony\Component\HttpKernel\HttpCache\ResponseCacheStrategyInterface") createCacheStrategy() Returns a new cache strategy instance. #### Return Value | | | | --- | --- | | [ResponseCacheStrategyInterface](responsecachestrategyinterface "Symfony\Component\HttpKernel\HttpCache\ResponseCacheStrategyInterface") | A ResponseCacheStrategyInterface instance | ### bool hasSurrogateCapability([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Checks that at least one surrogate has Surrogate capability. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | #### Return Value | | | | --- | --- | | bool | true if one surrogate has Surrogate capability, false otherwise | ### addSurrogateCapability([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Adds Surrogate-capability to the given Request. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | ### bool needsParsing([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Checks that the Response needs to be parsed for Surrogate tags. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | #### Return Value | | | | --- | --- | | bool | true if the Response needs to be parsed, false otherwise | ### string handle([HttpCache](httpcache "Symfony\Component\HttpKernel\HttpCache\HttpCache") $cache, string $uri, string $alt, bool $ignoreErrors) Handles a Surrogate from the cache. #### Parameters | | | | | --- | --- | --- | | [HttpCache](httpcache "Symfony\Component\HttpKernel\HttpCache\HttpCache") | $cache | An HttpCache instance | | string | $uri | The main URI | | string | $alt | An alternative URI | | bool | $ignoreErrors | Whether to ignore errors or not | #### Return Value | | | | --- | --- | | string | | #### Exceptions | | | | --- | --- | | [RuntimeException](http://php.net/RuntimeException) | | | [Exception](http://php.net/Exception) | | ### protected removeFromControl([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Remove the Surrogate from the Surrogate-Control header. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | symfony HttpCache HttpCache ========== class **HttpCache** implements [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface"), [TerminableInterface](../terminableinterface "Symfony\Component\HttpKernel\TerminableInterface") Cache provides HTTP caching. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, [StoreInterface](storeinterface "Symfony\Component\HttpKernel\HttpCache\StoreInterface") $store, [SurrogateInterface](surrogateinterface "Symfony\Component\HttpKernel\HttpCache\SurrogateInterface") $surrogate = null, array $options = array()) Constructor. | | | [StoreInterface](storeinterface "Symfony\Component\HttpKernel\HttpCache\StoreInterface") | [getStore](#method_getStore)() Gets the current store. | | | array | [getTraces](#method_getTraces)() Returns an array of events that took place during processing of the last request. | | | string | [getLog](#method_getLog)() Returns a log message for the events of the last request processing. | | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | [getRequest](#method_getRequest)() Gets the Request instance associated with the master request. | | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | [getKernel](#method_getKernel)() Gets the Kernel instance. | | | [SurrogateInterface](surrogateinterface "Symfony\Component\HttpKernel\HttpCache\SurrogateInterface") | [getSurrogate](#method_getSurrogate)() Gets the Surrogate instance. | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [handle](#method_handle)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int $type = HttpKernelInterface::MASTER\_REQUEST, bool $catch = true) Handles a Request to convert it to a Response. | | | | [terminate](#method_terminate)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Terminates a request/response cycle. | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [pass](#method_pass)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $catch = false) Forwards the Request to the backend without storing the Response in the cache. | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [invalidate](#method_invalidate)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $catch = false) Invalidates non-safe methods (like POST, PUT, and DELETE). | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [lookup](#method_lookup)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $catch = false) Lookups a Response from the cache for the given Request. | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [validate](#method_validate)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $entry, bool $catch = false) Validates that a cache entry is fresh. | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [fetch](#method_fetch)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $catch = false) Unconditionally fetches a fresh response from the backend and stores it in the cache if is cacheable. | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [forward](#method_forward)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $catch = false, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $entry = null) Forwards the Request to the backend and returns the Response. | | | bool | [isFreshEnough](#method_isFreshEnough)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $entry) Checks whether the cache entry is "fresh enough" to satisfy the Request. | | | bool | [lock](#method_lock)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $entry) Locks a Request during the call to the backend. | | | | [store](#method_store)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Writes the Response to the cache. | | | | [processResponseBody](#method_processResponseBody)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) | | Details ------- ### \_\_construct([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, [StoreInterface](storeinterface "Symfony\Component\HttpKernel\HttpCache\StoreInterface") $store, [SurrogateInterface](surrogateinterface "Symfony\Component\HttpKernel\HttpCache\SurrogateInterface") $surrogate = null, array $options = array()) Constructor. The available options are: * debug: If true, the traces are added as a HTTP header to ease debugging * default\_ttl The number of seconds that a cache entry should be considered fresh when no explicit freshness information is provided in a response. Explicit Cache-Control or Expires headers override this value. (default: 0) * private\_headers Set of request headers that trigger "private" cache-control behavior on responses that don't explicitly state whether the response is public or private via a Cache-Control directive. (default: Authorization and Cookie) * allow\_reload Specifies whether the client can force a cache reload by including a Cache-Control "no-cache" directive in the request. Set it to `true` for compliance with RFC 2616. (default: false) * allow\_revalidate Specifies whether the client can force a cache revalidate by including a Cache-Control "max-age=0" directive in the request. Set it to `true` for compliance with RFC 2616. (default: false) * stale\_while\_revalidate Specifies the default number of seconds (the granularity is the second as the Response TTL precision is a second) during which the cache can immediately return a stale response while it revalidates it in the background (default: 2). This setting is overridden by the stale-while-revalidate HTTP Cache-Control extension (see RFC 5861). * stale\_if\_error Specifies the default number of seconds (the granularity is the second) during which the cache can serve a stale response when an error is encountered (default: 60). This setting is overridden by the stale-if-error HTTP Cache-Control extension (see RFC 5861). #### Parameters | | | | | --- | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | $kernel | | | [StoreInterface](storeinterface "Symfony\Component\HttpKernel\HttpCache\StoreInterface") | $store | | | [SurrogateInterface](surrogateinterface "Symfony\Component\HttpKernel\HttpCache\SurrogateInterface") | $surrogate | | | array | $options | | ### [StoreInterface](storeinterface "Symfony\Component\HttpKernel\HttpCache\StoreInterface") getStore() Gets the current store. #### Return Value | | | | --- | --- | | [StoreInterface](storeinterface "Symfony\Component\HttpKernel\HttpCache\StoreInterface") | $store A StoreInterface instance | ### array getTraces() Returns an array of events that took place during processing of the last request. #### Return Value | | | | --- | --- | | array | An array of events | ### string getLog() Returns a log message for the events of the last request processing. #### Return Value | | | | --- | --- | | string | A log message | ### [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") getRequest() Gets the Request instance associated with the master request. #### Return Value | | | | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | A Request instance | ### [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") getKernel() Gets the Kernel instance. #### Return Value | | | | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | An HttpKernelInterface instance | ### [SurrogateInterface](surrogateinterface "Symfony\Component\HttpKernel\HttpCache\SurrogateInterface") getSurrogate() Gets the Surrogate instance. #### Return Value | | | | --- | --- | | [SurrogateInterface](surrogateinterface "Symfony\Component\HttpKernel\HttpCache\SurrogateInterface") | A Surrogate instance | #### Exceptions | | | | --- | --- | | [LogicException](http://php.net/LogicException) | | ### [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") handle([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int $type = HttpKernelInterface::MASTER\_REQUEST, bool $catch = true) Handles a Request to convert it to a Response. When $catch is true, the implementation must catch all exceptions and do its best to convert them to a Response instance. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | int | $type | The type of the request (one of HttpKernelInterface::MASTER\_REQUEST or HttpKernelInterface::SUB\_REQUEST) | | bool | $catch | Whether to catch exceptions or not | #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | A Response instance | #### Exceptions | | | | --- | --- | | [Exception](http://php.net/Exception) | When an Exception occurs during processing | ### terminate([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Terminates a request/response cycle. Should be called after sending the response and before shutting down the kernel. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | ### protected [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") pass([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $catch = false) Forwards the Request to the backend without storing the Response in the cache. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | bool | $catch | Whether to process exceptions | #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | A Response instance | ### protected [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") invalidate([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $catch = false) Invalidates non-safe methods (like POST, PUT, and DELETE). #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | bool | $catch | Whether to process exceptions | #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | A Response instance | #### Exceptions | | | | --- | --- | | [Exception](http://php.net/Exception) | | #### See also | | | | --- | --- | | RFC2616 | 13.10 | ### protected [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") lookup([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $catch = false) Lookups a Response from the cache for the given Request. When a matching cache entry is found and is fresh, it uses it as the response without forwarding any request to the backend. When a matching cache entry is found but is stale, it attempts to "validate" the entry with the backend using conditional GET. When no matching cache entry is found, it triggers "miss" processing. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | bool | $catch | Whether to process exceptions | #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | A Response instance | #### Exceptions | | | | --- | --- | | [Exception](http://php.net/Exception) | | ### protected [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") validate([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $entry, bool $catch = false) Validates that a cache entry is fresh. The original request is used as a template for a conditional GET request with the backend. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $entry | A Response instance to validate | | bool | $catch | Whether to process exceptions | #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | A Response instance | ### protected [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") fetch([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $catch = false) Unconditionally fetches a fresh response from the backend and stores it in the cache if is cacheable. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | bool | $catch | Whether to process exceptions | #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | A Response instance | ### protected [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") forward([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, bool $catch = false, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $entry = null) Forwards the Request to the backend and returns the Response. All backend requests (cache passes, fetches, cache validations) run through this method. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | A Request instance | | bool | $catch | Whether to catch exceptions or not | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $entry | A Response instance (the stale entry if present, null otherwise) | #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | A Response instance | ### protected bool isFreshEnough([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $entry) Checks whether the cache entry is "fresh enough" to satisfy the Request. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $entry | | #### Return Value | | | | --- | --- | | bool | true if the cache entry if fresh enough, false otherwise | ### protected bool lock([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $entry) Locks a Request during the call to the backend. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $entry | | #### Return Value | | | | --- | --- | | bool | true if the cache entry can be returned even if it is staled, false otherwise | ### protected store([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Writes the Response to the cache. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | #### Exceptions | | | | --- | --- | | [Exception](http://php.net/Exception) | | ### protected processResponseBody([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | |
programming_docs
symfony Esi Esi ==== class **Esi** extends [AbstractSurrogate](abstractsurrogate "Symfony\Component\HttpKernel\HttpCache\AbstractSurrogate") Esi implements the ESI capabilities to Request and Response instances. For more information, read the following W3C notes: * ESI Language Specification 1.0 (http://www.w3.org/TR/esi-lang) * Edge Architecture Specification (http://www.w3.org/TR/edge-arch) Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $contentTypes | | from [AbstractSurrogate](abstractsurrogate#property_contentTypes "Symfony\Component\HttpKernel\HttpCache\AbstractSurrogate") | | protected | $phpEscapeMap | | from [AbstractSurrogate](abstractsurrogate#property_phpEscapeMap "Symfony\Component\HttpKernel\HttpCache\AbstractSurrogate") | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(array $contentTypes = array('text/html', 'text/xml', 'application/xhtml+xml', 'application/xml')) | from [AbstractSurrogate](abstractsurrogate#method___construct "Symfony\Component\HttpKernel\HttpCache\AbstractSurrogate") | | [ResponseCacheStrategyInterface](responsecachestrategyinterface "Symfony\Component\HttpKernel\HttpCache\ResponseCacheStrategyInterface") | [createCacheStrategy](#method_createCacheStrategy)() Returns a new cache strategy instance. | from [AbstractSurrogate](abstractsurrogate#method_createCacheStrategy "Symfony\Component\HttpKernel\HttpCache\AbstractSurrogate") | | bool | [hasSurrogateCapability](#method_hasSurrogateCapability)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Checks that at least one surrogate has Surrogate capability. | from [AbstractSurrogate](abstractsurrogate#method_hasSurrogateCapability "Symfony\Component\HttpKernel\HttpCache\AbstractSurrogate") | | | [addSurrogateCapability](#method_addSurrogateCapability)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Adds Surrogate-capability to the given Request. | from [AbstractSurrogate](abstractsurrogate#method_addSurrogateCapability "Symfony\Component\HttpKernel\HttpCache\AbstractSurrogate") | | bool | [needsParsing](#method_needsParsing)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Checks that the Response needs to be parsed for Surrogate tags. | from [AbstractSurrogate](abstractsurrogate#method_needsParsing "Symfony\Component\HttpKernel\HttpCache\AbstractSurrogate") | | string | [handle](#method_handle)([HttpCache](httpcache "Symfony\Component\HttpKernel\HttpCache\HttpCache") $cache, string $uri, string $alt, bool $ignoreErrors) Handles a Surrogate from the cache. | from [AbstractSurrogate](abstractsurrogate#method_handle "Symfony\Component\HttpKernel\HttpCache\AbstractSurrogate") | | | [removeFromControl](#method_removeFromControl)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Remove the Surrogate from the Surrogate-Control header. | from [AbstractSurrogate](abstractsurrogate#method_removeFromControl "Symfony\Component\HttpKernel\HttpCache\AbstractSurrogate") | | string | [getName](#method_getName)() Returns surrogate name. | | | | [addSurrogateControl](#method_addSurrogateControl)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Adds HTTP headers to specify that the Response needs to be parsed for Surrogate. | | | string | [renderIncludeTag](#method_renderIncludeTag)(string $uri, string $alt = null, bool $ignoreErrors = true, string $comment = '') Renders a Surrogate tag. | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [process](#method_process)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Replaces a Response Surrogate tags with the included resource content. | | Details ------- ### \_\_construct(array $contentTypes = array('text/html', 'text/xml', 'application/xhtml+xml', 'application/xml')) #### Parameters | | | | | --- | --- | --- | | array | $contentTypes | An array of content-type that should be parsed for Surrogate information (default: text/html, text/xml, application/xhtml+xml, and application/xml) | ### [ResponseCacheStrategyInterface](responsecachestrategyinterface "Symfony\Component\HttpKernel\HttpCache\ResponseCacheStrategyInterface") createCacheStrategy() Returns a new cache strategy instance. #### Return Value | | | | --- | --- | | [ResponseCacheStrategyInterface](responsecachestrategyinterface "Symfony\Component\HttpKernel\HttpCache\ResponseCacheStrategyInterface") | A ResponseCacheStrategyInterface instance | ### bool hasSurrogateCapability([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Checks that at least one surrogate has Surrogate capability. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | #### Return Value | | | | --- | --- | | bool | true if one surrogate has Surrogate capability, false otherwise | ### addSurrogateCapability([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Adds Surrogate-capability to the given Request. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | ### bool needsParsing([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Checks that the Response needs to be parsed for Surrogate tags. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | #### Return Value | | | | --- | --- | | bool | true if the Response needs to be parsed, false otherwise | ### string handle([HttpCache](httpcache "Symfony\Component\HttpKernel\HttpCache\HttpCache") $cache, string $uri, string $alt, bool $ignoreErrors) Handles a Surrogate from the cache. #### Parameters | | | | | --- | --- | --- | | [HttpCache](httpcache "Symfony\Component\HttpKernel\HttpCache\HttpCache") | $cache | An HttpCache instance | | string | $uri | The main URI | | string | $alt | An alternative URI | | bool | $ignoreErrors | Whether to ignore errors or not | #### Return Value | | | | --- | --- | | string | | #### Exceptions | | | | --- | --- | | [RuntimeException](http://php.net/RuntimeException) | | | [Exception](http://php.net/Exception) | | ### protected removeFromControl([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Remove the Surrogate from the Surrogate-Control header. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | ### string getName() Returns surrogate name. #### Return Value | | | | --- | --- | | string | | ### addSurrogateControl([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Adds HTTP headers to specify that the Response needs to be parsed for Surrogate. This method only adds an Surrogate HTTP header if the Response has some Surrogate tags. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | ### string renderIncludeTag(string $uri, string $alt = null, bool $ignoreErrors = true, string $comment = '') Renders a Surrogate tag. #### Parameters | | | | | --- | --- | --- | | string | $uri | A URI | | string | $alt | An alternate URI | | bool | $ignoreErrors | Whether to ignore errors or not | | string | $comment | A comment to add as an esi:include tag | #### Return Value | | | | --- | --- | | string | | ### [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") process([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Replaces a Response Surrogate tags with the included resource content. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | | symfony SurrogateInterface SurrogateInterface =================== interface **SurrogateInterface** Methods ------- | | | | | --- | --- | --- | | string | [getName](#method_getName)() Returns surrogate name. | | | [ResponseCacheStrategyInterface](responsecachestrategyinterface "Symfony\Component\HttpKernel\HttpCache\ResponseCacheStrategyInterface") | [createCacheStrategy](#method_createCacheStrategy)() Returns a new cache strategy instance. | | | bool | [hasSurrogateCapability](#method_hasSurrogateCapability)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Checks that at least one surrogate has Surrogate capability. | | | | [addSurrogateCapability](#method_addSurrogateCapability)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Adds Surrogate-capability to the given Request. | | | | [addSurrogateControl](#method_addSurrogateControl)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Adds HTTP headers to specify that the Response needs to be parsed for Surrogate. | | | bool | [needsParsing](#method_needsParsing)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Checks that the Response needs to be parsed for Surrogate tags. | | | string | [renderIncludeTag](#method_renderIncludeTag)(string $uri, string $alt = null, bool $ignoreErrors = true, string $comment = '') Renders a Surrogate tag. | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [process](#method_process)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Replaces a Response Surrogate tags with the included resource content. | | | string | [handle](#method_handle)([HttpCache](httpcache "Symfony\Component\HttpKernel\HttpCache\HttpCache") $cache, string $uri, string $alt, bool $ignoreErrors) Handles a Surrogate from the cache. | | Details ------- ### string getName() Returns surrogate name. #### Return Value | | | | --- | --- | | string | | ### [ResponseCacheStrategyInterface](responsecachestrategyinterface "Symfony\Component\HttpKernel\HttpCache\ResponseCacheStrategyInterface") createCacheStrategy() Returns a new cache strategy instance. #### Return Value | | | | --- | --- | | [ResponseCacheStrategyInterface](responsecachestrategyinterface "Symfony\Component\HttpKernel\HttpCache\ResponseCacheStrategyInterface") | A ResponseCacheStrategyInterface instance | ### bool hasSurrogateCapability([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Checks that at least one surrogate has Surrogate capability. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | #### Return Value | | | | --- | --- | | bool | true if one surrogate has Surrogate capability, false otherwise | ### addSurrogateCapability([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Adds Surrogate-capability to the given Request. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | ### addSurrogateControl([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Adds HTTP headers to specify that the Response needs to be parsed for Surrogate. This method only adds an Surrogate HTTP header if the Response has some Surrogate tags. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | ### bool needsParsing([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Checks that the Response needs to be parsed for Surrogate tags. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | #### Return Value | | | | --- | --- | | bool | true if the Response needs to be parsed, false otherwise | ### string renderIncludeTag(string $uri, string $alt = null, bool $ignoreErrors = true, string $comment = '') Renders a Surrogate tag. #### Parameters | | | | | --- | --- | --- | | string | $uri | A URI | | string | $alt | An alternate URI | | bool | $ignoreErrors | Whether to ignore errors or not | | string | $comment | A comment to add as an esi:include tag | #### Return Value | | | | --- | --- | | string | | ### [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") process([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Replaces a Response Surrogate tags with the included resource content. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | | ### string handle([HttpCache](httpcache "Symfony\Component\HttpKernel\HttpCache\HttpCache") $cache, string $uri, string $alt, bool $ignoreErrors) Handles a Surrogate from the cache. #### Parameters | | | | | --- | --- | --- | | [HttpCache](httpcache "Symfony\Component\HttpKernel\HttpCache\HttpCache") | $cache | An HttpCache instance | | string | $uri | The main URI | | string | $alt | An alternative URI | | bool | $ignoreErrors | Whether to ignore errors or not | #### Return Value | | | | --- | --- | | string | | #### Exceptions | | | | --- | --- | | [RuntimeException](http://php.net/RuntimeException) | | | [Exception](http://php.net/Exception) | | symfony DebugLoggerInterface DebugLoggerInterface ===================== interface **DebugLoggerInterface** DebugLoggerInterface. Methods ------- | | | | | --- | --- | --- | | array | [getLogs](#method_getLogs)() Returns an array of logs. | | | int | [countErrors](#method_countErrors)() Returns the number of errors. | | | | [clear](#method_clear)() Removes all log records. | | Details ------- ### array getLogs() Returns an array of logs. A log is an array with the following mandatory keys: timestamp, message, priority, and priorityName. It can also have an optional context key containing an array. #### Return Value | | | | --- | --- | | array | An array of logs | ### int countErrors() Returns the number of errors. #### Return Value | | | | --- | --- | | int | The number of errors | ### clear() Removes all log records. symfony Logger Logger ======= class **Logger** extends AbstractLogger Minimalist PSR-3 logger designed to write in stderr or any other stream. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $minLevel = null, $output = 'php://stderr', callable $formatter = null) | | | | [log](#method_log)($level, $message, array $context = array()) {@inheritdoc} | | Details ------- ### \_\_construct(string $minLevel = null, $output = 'php://stderr', callable $formatter = null) #### Parameters | | | | | --- | --- | --- | | string | $minLevel | | | | $output | | | callable | $formatter | | ### log($level, $message, array $context = array()) {@inheritdoc} #### Parameters | | | | | --- | --- | --- | | | $level | | | | $message | | | array | $context | | symfony Profile Profile ======== class **Profile** Profile. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $token) | | | | [setToken](#method_setToken)(string $token) Sets the token. | | | string | [getToken](#method_getToken)() Gets the token. | | | | [setParent](#method_setParent)([Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") $parent) Sets the parent token. | | | [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") | [getParent](#method_getParent)() Returns the parent profile. | | | string|null | [getParentToken](#method_getParentToken)() Returns the parent token. | | | string | [getIp](#method_getIp)() Returns the IP. | | | | [setIp](#method_setIp)(string $ip) Sets the IP. | | | string | [getMethod](#method_getMethod)() Returns the request method. | | | | [setMethod](#method_setMethod)($method) | | | string | [getUrl](#method_getUrl)() Returns the URL. | | | | [setUrl](#method_setUrl)($url) | | | int | [getTime](#method_getTime)() Returns the time. | | | | [setTime](#method_setTime)(int $time) | | | | [setStatusCode](#method_setStatusCode)(int $statusCode) | | | int | [getStatusCode](#method_getStatusCode)() | | | [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile")[] | [getChildren](#method_getChildren)() Finds children profilers. | | | | [setChildren](#method_setChildren)(array $children) Sets children profiler. | | | | [addChild](#method_addChild)([Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") $child) Adds the child token. | | | [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile")|null | [getChildByToken](#method_getChildByToken)(string $token) | | | [DataCollectorInterface](../datacollector/datacollectorinterface "Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface") | [getCollector](#method_getCollector)(string $name) Gets a Collector by name. | | | [DataCollectorInterface](../datacollector/datacollectorinterface "Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface")[] | [getCollectors](#method_getCollectors)() Gets the Collectors associated with this profile. | | | | [setCollectors](#method_setCollectors)(array $collectors) Sets the Collectors associated with this profile. | | | | [addCollector](#method_addCollector)([DataCollectorInterface](../datacollector/datacollectorinterface "Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface") $collector) Adds a Collector. | | | bool | [hasCollector](#method_hasCollector)(string $name) Returns true if a Collector for the given name exists. | | | | [\_\_sleep](#method___sleep)() | | Details ------- ### \_\_construct(string $token) #### Parameters | | | | | --- | --- | --- | | string | $token | | ### setToken(string $token) Sets the token. #### Parameters | | | | | --- | --- | --- | | string | $token | The token | ### string getToken() Gets the token. #### Return Value | | | | --- | --- | | string | The token | ### setParent([Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") $parent) Sets the parent token. #### Parameters | | | | | --- | --- | --- | | [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") | $parent | | ### [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") getParent() Returns the parent profile. #### Return Value | | | | --- | --- | | [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") | | ### string|null getParentToken() Returns the parent token. #### Return Value | | | | --- | --- | | string|null | The parent token | ### string getIp() Returns the IP. #### Return Value | | | | --- | --- | | string | The IP | ### setIp(string $ip) Sets the IP. #### Parameters | | | | | --- | --- | --- | | string | $ip | | ### string getMethod() Returns the request method. #### Return Value | | | | --- | --- | | string | The request method | ### setMethod($method) #### Parameters | | | | | --- | --- | --- | | | $method | | ### string getUrl() Returns the URL. #### Return Value | | | | --- | --- | | string | The URL | ### setUrl($url) #### Parameters | | | | | --- | --- | --- | | | $url | | ### int getTime() Returns the time. #### Return Value | | | | --- | --- | | int | The time | ### setTime(int $time) #### Parameters | | | | | --- | --- | --- | | int | $time | The time | ### setStatusCode(int $statusCode) #### Parameters | | | | | --- | --- | --- | | int | $statusCode | | ### int getStatusCode() #### Return Value | | | | --- | --- | | int | | ### [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile")[] getChildren() Finds children profilers. #### Return Value | | | | --- | --- | | [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile")[] | | ### setChildren(array $children) Sets children profiler. #### Parameters | | | | | --- | --- | --- | | array | $children | | ### addChild([Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") $child) Adds the child token. #### Parameters | | | | | --- | --- | --- | | [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") | $child | | ### [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile")|null getChildByToken(string $token) #### Parameters | | | | | --- | --- | --- | | string | $token | | #### Return Value | | | | --- | --- | | [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile")|null | | ### [DataCollectorInterface](../datacollector/datacollectorinterface "Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface") getCollector(string $name) Gets a Collector by name. #### Parameters | | | | | --- | --- | --- | | string | $name | A collector name | #### Return Value | | | | --- | --- | | [DataCollectorInterface](../datacollector/datacollectorinterface "Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface") | A DataCollectorInterface instance | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](http://php.net/InvalidArgumentException) | if the collector does not exist | ### [DataCollectorInterface](../datacollector/datacollectorinterface "Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface")[] getCollectors() Gets the Collectors associated with this profile. #### Return Value | | | | --- | --- | | [DataCollectorInterface](../datacollector/datacollectorinterface "Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface")[] | | ### setCollectors(array $collectors) Sets the Collectors associated with this profile. #### Parameters | | | | | --- | --- | --- | | array | $collectors | | ### addCollector([DataCollectorInterface](../datacollector/datacollectorinterface "Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface") $collector) Adds a Collector. #### Parameters | | | | | --- | --- | --- | | [DataCollectorInterface](../datacollector/datacollectorinterface "Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface") | $collector | | ### bool hasCollector(string $name) Returns true if a Collector for the given name exists. #### Parameters | | | | | --- | --- | --- | | string | $name | A collector name | #### Return Value | | | | --- | --- | | bool | | ### \_\_sleep()
programming_docs
symfony ProfilerStorageInterface ProfilerStorageInterface ========================= interface **ProfilerStorageInterface** ProfilerStorageInterface. Methods ------- | | | | | --- | --- | --- | | array | [find](#method_find)(string $ip, string $url, string $limit, string $method, int|null $start = null, int|null $end = null) Finds profiler tokens for the given criteria. | | | [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") | [read](#method_read)(string $token) Reads data associated with the given token. | | | bool | [write](#method_write)([Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") $profile) Saves a Profile. | | | | [purge](#method_purge)() Purges all data from the database. | | Details ------- ### array find(string $ip, string $url, string $limit, string $method, int|null $start = null, int|null $end = null) Finds profiler tokens for the given criteria. #### Parameters | | | | | --- | --- | --- | | string | $ip | The IP | | string | $url | The URL | | string | $limit | The maximum number of tokens to return | | string | $method | The request method | | int|null | $start | The start date to search from | | int|null | $end | The end date to search to | #### Return Value | | | | --- | --- | | array | An array of tokens | ### [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") read(string $token) Reads data associated with the given token. The method returns false if the token does not exist in the storage. #### Parameters | | | | | --- | --- | --- | | string | $token | A token | #### Return Value | | | | --- | --- | | [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") | The profile associated with token | ### bool write([Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") $profile) Saves a Profile. #### Parameters | | | | | --- | --- | --- | | [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") | $profile | | #### Return Value | | | | --- | --- | | bool | Write operation successful | ### purge() Purges all data from the database. symfony Profiler Profiler ========= class **Profiler** Profiler. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([ProfilerStorageInterface](profilerstorageinterface "Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface") $storage, LoggerInterface $logger = null, bool $enable = true) | | | | [disable](#method_disable)() Disables the profiler. | | | | [enable](#method_enable)() Enables the profiler. | | | [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile")|false | [loadProfileFromResponse](#method_loadProfileFromResponse)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Loads the Profile for the given Response. | | | [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") | [loadProfile](#method_loadProfile)(string $token) Loads the Profile for the given token. | | | bool | [saveProfile](#method_saveProfile)([Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") $profile) Saves a Profile. | | | | [purge](#method_purge)() Purges all data from the storage. | | | array | [find](#method_find)(string $ip, string $url, string $limit, string $method, string $start, string $end, string $statusCode = null) Finds profiler tokens for the given criteria. | | | [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile")|null | [collect](#method_collect)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Response. | | | | [reset](#method_reset)() | | | array | [all](#method_all)() Gets the Collectors associated with this profiler. | | | | [set](#method_set)(array $collectors = array()) Sets the Collectors associated with this profiler. | | | | [add](#method_add)([DataCollectorInterface](../datacollector/datacollectorinterface "Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface") $collector) Adds a Collector. | | | bool | [has](#method_has)(string $name) Returns true if a Collector for the given name exists. | | | [DataCollectorInterface](../datacollector/datacollectorinterface "Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface") | [get](#method_get)(string $name) Gets a Collector by name. | | Details ------- ### \_\_construct([ProfilerStorageInterface](profilerstorageinterface "Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface") $storage, LoggerInterface $logger = null, bool $enable = true) #### Parameters | | | | | --- | --- | --- | | [ProfilerStorageInterface](profilerstorageinterface "Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface") | $storage | | | LoggerInterface | $logger | | | bool | $enable | | ### disable() Disables the profiler. ### enable() Enables the profiler. ### [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile")|false loadProfileFromResponse([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Loads the Profile for the given Response. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | #### Return Value | | | | --- | --- | | [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile")|false | A Profile instance | ### [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") loadProfile(string $token) Loads the Profile for the given token. #### Parameters | | | | | --- | --- | --- | | string | $token | A token | #### Return Value | | | | --- | --- | | [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") | A Profile instance | ### bool saveProfile([Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") $profile) Saves a Profile. #### Parameters | | | | | --- | --- | --- | | [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") | $profile | | #### Return Value | | | | --- | --- | | bool | | ### purge() Purges all data from the storage. ### array find(string $ip, string $url, string $limit, string $method, string $start, string $end, string $statusCode = null) Finds profiler tokens for the given criteria. #### Parameters | | | | | --- | --- | --- | | string | $ip | The IP | | string | $url | The URL | | string | $limit | The maximum number of tokens to return | | string | $method | The request method | | string | $start | The start date to search from | | string | $end | The end date to search to | | string | $statusCode | The request status code | #### Return Value | | | | --- | --- | | array | An array of tokens | #### See also | | | | --- | --- | | <http://php.net/manual/en/datetime.formats.php> | for the supported date/time formats | ### [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile")|null collect([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response, [Exception](http://php.net/Exception) $exception = null) Collects data for the given Response. #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | | [Exception](http://php.net/Exception) | $exception | | #### Return Value | | | | --- | --- | | [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile")|null | A Profile instance or null if the profiler is disabled | ### reset() ### array all() Gets the Collectors associated with this profiler. #### Return Value | | | | --- | --- | | array | An array of collectors | ### set(array $collectors = array()) Sets the Collectors associated with this profiler. #### Parameters | | | | | --- | --- | --- | | array | $collectors | An array of collectors | ### add([DataCollectorInterface](../datacollector/datacollectorinterface "Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface") $collector) Adds a Collector. #### Parameters | | | | | --- | --- | --- | | [DataCollectorInterface](../datacollector/datacollectorinterface "Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface") | $collector | | ### bool has(string $name) Returns true if a Collector for the given name exists. #### Parameters | | | | | --- | --- | --- | | string | $name | A collector name | #### Return Value | | | | --- | --- | | bool | | ### [DataCollectorInterface](../datacollector/datacollectorinterface "Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface") get(string $name) Gets a Collector by name. #### Parameters | | | | | --- | --- | --- | | string | $name | A collector name | #### Return Value | | | | --- | --- | | [DataCollectorInterface](../datacollector/datacollectorinterface "Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface") | A DataCollectorInterface instance | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](http://php.net/InvalidArgumentException) | if the collector does not exist | symfony FileProfilerStorage FileProfilerStorage ==================== class **FileProfilerStorage** implements [ProfilerStorageInterface](profilerstorageinterface "Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface") Storage for profiler using files. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $dsn) Constructs the file storage using a "dsn-like" path. | | | array | [find](#method_find)(string $ip, string $url, string $limit, string $method, int|null $start = null, int|null $end = null, $statusCode = null) Finds profiler tokens for the given criteria. | | | | [purge](#method_purge)() Purges all data from the database. | | | [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") | [read](#method_read)(string $token) Reads data associated with the given token. | | | bool | [write](#method_write)([Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") $profile) Saves a Profile. | | | string | [getFilename](#method_getFilename)(string $token) Gets filename to store data, associated to the token. | | | string | [getIndexFilename](#method_getIndexFilename)() Gets the index filename. | | | mixed | [readLineFromFile](#method_readLineFromFile)(resource $file) Reads a line in the file, backward. | | | | [createProfileFromData](#method_createProfileFromData)($token, $data, $parent = null) | | Details ------- ### \_\_construct(string $dsn) Constructs the file storage using a "dsn-like" path. Example : "file:/path/to/the/storage/folder" #### Parameters | | | | | --- | --- | --- | | string | $dsn | | #### Exceptions | | | | --- | --- | | [RuntimeException](http://php.net/RuntimeException) | | ### array find(string $ip, string $url, string $limit, string $method, int|null $start = null, int|null $end = null, $statusCode = null) Finds profiler tokens for the given criteria. #### Parameters | | | | | --- | --- | --- | | string | $ip | The IP | | string | $url | The URL | | string | $limit | The maximum number of tokens to return | | string | $method | The request method | | int|null | $start | The start date to search from | | int|null | $end | The end date to search to | | | $statusCode | | #### Return Value | | | | --- | --- | | array | An array of tokens | ### purge() Purges all data from the database. ### [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") read(string $token) Reads data associated with the given token. The method returns false if the token does not exist in the storage. #### Parameters | | | | | --- | --- | --- | | string | $token | A token | #### Return Value | | | | --- | --- | | [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") | The profile associated with token | ### bool write([Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") $profile) Saves a Profile. #### Parameters | | | | | --- | --- | --- | | [Profile](profile "Symfony\Component\HttpKernel\Profiler\Profile") | $profile | | #### Return Value | | | | --- | --- | | bool | Write operation successful | ### protected string getFilename(string $token) Gets filename to store data, associated to the token. #### Parameters | | | | | --- | --- | --- | | string | $token | | #### Return Value | | | | --- | --- | | string | The profile filename | ### protected string getIndexFilename() Gets the index filename. #### Return Value | | | | --- | --- | | string | The index filename | ### protected mixed readLineFromFile(resource $file) Reads a line in the file, backward. This function automatically skips the empty lines and do not include the line return in result value. #### Parameters | | | | | --- | --- | --- | | resource | $file | The file resource, with the pointer placed at the end of the line to read | #### Return Value | | | | --- | --- | | mixed | A string representing the line or null if beginning of file is reached | ### protected createProfileFromData($token, $data, $parent = null) #### Parameters | | | | | --- | --- | --- | | | $token | | | | $data | | | | $parent | | symfony LoggerPass LoggerPass =========== class **LoggerPass** implements [CompilerPassInterface](../../dependencyinjection/compiler/compilerpassinterface "Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface") Registers the default logger if necessary. Methods ------- | | | | | --- | --- | --- | | | [process](#method_process)([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) You can modify the container here before it is dumped to PHP code. | | Details ------- ### process([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) You can modify the container here before it is dumped to PHP code. #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | symfony Extension Extension ========== abstract class **Extension** extends [Extension](../../dependencyinjection/extension/extension "Symfony\Component\DependencyInjection\Extension\Extension") Allow adding classes to the class cache. Methods ------- | | | | | --- | --- | --- | | string | [getXsdValidationBasePath](#method_getXsdValidationBasePath)() Returns the base path for the XSD files. | from [Extension](../../dependencyinjection/extension/extension#method_getXsdValidationBasePath "Symfony\Component\DependencyInjection\Extension\Extension") | | string | [getNamespace](#method_getNamespace)() Returns the namespace to be used for this extension (XML namespace). | from [Extension](../../dependencyinjection/extension/extension#method_getNamespace "Symfony\Component\DependencyInjection\Extension\Extension") | | string | [getAlias](#method_getAlias)() Returns the recommended alias to use in XML. | from [Extension](../../dependencyinjection/extension/extension#method_getAlias "Symfony\Component\DependencyInjection\Extension\Extension") | | [ConfigurationInterface](../../config/definition/configurationinterface "Symfony\Component\Config\Definition\ConfigurationInterface")|null | [getConfiguration](#method_getConfiguration)(array $config, [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Returns extension configuration. | from [Extension](../../dependencyinjection/extension/extension#method_getConfiguration "Symfony\Component\DependencyInjection\Extension\Extension") | | | [processConfiguration](#method_processConfiguration)([ConfigurationInterface](../../config/definition/configurationinterface "Symfony\Component\Config\Definition\ConfigurationInterface") $configuration, array $configs) | from [Extension](../../dependencyinjection/extension/extension#method_processConfiguration "Symfony\Component\DependencyInjection\Extension\Extension") | | | [getProcessedConfigs](#method_getProcessedConfigs)() | from [Extension](../../dependencyinjection/extension/extension#method_getProcessedConfigs "Symfony\Component\DependencyInjection\Extension\Extension") | | bool | [isConfigEnabled](#method_isConfigEnabled)([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container, array $config) | from [Extension](../../dependencyinjection/extension/extension#method_isConfigEnabled "Symfony\Component\DependencyInjection\Extension\Extension") | | array | [getAnnotatedClassesToCompile](#method_getAnnotatedClassesToCompile)() Gets the annotated classes to cache. | | | | [addAnnotatedClassesToCompile](#method_addAnnotatedClassesToCompile)(array $annotatedClasses) Adds annotated classes to the class cache. | | Details ------- ### string getXsdValidationBasePath() Returns the base path for the XSD files. #### Return Value | | | | --- | --- | | string | The XSD base path | ### string getNamespace() Returns the namespace to be used for this extension (XML namespace). #### Return Value | | | | --- | --- | | string | The XML namespace | ### string getAlias() Returns the recommended alias to use in XML. This alias is also the mandatory prefix to use when using YAML. This convention is to remove the "Extension" postfix from the class name and then lowercase and underscore the result. So: ``` AcmeHelloExtension ``` becomes ``` acme_hello ``` This can be overridden in a sub-class to specify the alias manually. #### Return Value | | | | --- | --- | | string | The alias | #### Exceptions | | | | --- | --- | | [BadMethodCallException](../../dependencyinjection/exception/badmethodcallexception "Symfony\Component\DependencyInjection\Exception\BadMethodCallException") | When the extension name does not follow conventions | ### [ConfigurationInterface](../../config/definition/configurationinterface "Symfony\Component\Config\Definition\ConfigurationInterface")|null getConfiguration(array $config, [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Returns extension configuration. #### Parameters | | | | | --- | --- | --- | | array | $config | | | [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | #### Return Value | | | | --- | --- | | [ConfigurationInterface](../../config/definition/configurationinterface "Symfony\Component\Config\Definition\ConfigurationInterface")|null | The configuration or null | ### final protected processConfiguration([ConfigurationInterface](../../config/definition/configurationinterface "Symfony\Component\Config\Definition\ConfigurationInterface") $configuration, array $configs) #### Parameters | | | | | --- | --- | --- | | [ConfigurationInterface](../../config/definition/configurationinterface "Symfony\Component\Config\Definition\ConfigurationInterface") | $configuration | | | array | $configs | | ### final getProcessedConfigs() ### protected bool isConfigEnabled([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container, array $config) #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | | array | $config | | #### Return Value | | | | --- | --- | | bool | Whether the configuration is enabled | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](../../dependencyinjection/exception/invalidargumentexception "Symfony\Component\DependencyInjection\Exception\InvalidArgumentException") | When the config is not enableable | ### array getAnnotatedClassesToCompile() Gets the annotated classes to cache. #### Return Value | | | | --- | --- | | array | An array of classes | ### addAnnotatedClassesToCompile(array $annotatedClasses) Adds annotated classes to the class cache. #### Parameters | | | | | --- | --- | --- | | array | $annotatedClasses | An array of class patterns |
programming_docs
symfony ControllerArgumentValueResolverPass ControllerArgumentValueResolverPass ==================================== class **ControllerArgumentValueResolverPass** implements [CompilerPassInterface](../../dependencyinjection/compiler/compilerpassinterface "Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface") Gathers and configures the argument value resolvers. Traits ------ | | | | --- | --- | | [PriorityTaggedServiceTrait](../../dependencyinjection/compiler/prioritytaggedservicetrait "Symfony\Component\DependencyInjection\Compiler\PriorityTaggedServiceTrait") | Trait that allows a generic method to find and sort service by priority option in the tag. | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $argumentResolverService = 'argument\_resolver', string $argumentValueResolverTag = 'controller.argument\_value\_resolver', string $traceableResolverStopwatch = 'debug.stopwatch') | | | | [process](#method_process)([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) You can modify the container here before it is dumped to PHP code. | | Details ------- ### \_\_construct(string $argumentResolverService = 'argument\_resolver', string $argumentValueResolverTag = 'controller.argument\_value\_resolver', string $traceableResolverStopwatch = 'debug.stopwatch') #### Parameters | | | | | --- | --- | --- | | string | $argumentResolverService | | | string | $argumentValueResolverTag | | | string | $traceableResolverStopwatch | | ### process([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) You can modify the container here before it is dumped to PHP code. #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | symfony ConfigurableExtension ConfigurableExtension ====================== abstract class **ConfigurableExtension** extends [Extension](extension "Symfony\Component\HttpKernel\DependencyInjection\Extension") This extension sub-class provides first-class integration with the Config/Definition Component. You can use this as base class if a) you use the Config/Definition component for configuration, b) your configuration class is named "Configuration", and c) the configuration class resides in the DependencyInjection sub-folder. Methods ------- | | | | | --- | --- | --- | | string | [getXsdValidationBasePath](#method_getXsdValidationBasePath)() Returns the base path for the XSD files. | from [Extension](../../dependencyinjection/extension/extension#method_getXsdValidationBasePath "Symfony\Component\DependencyInjection\Extension\Extension") | | string | [getNamespace](#method_getNamespace)() Returns the namespace to be used for this extension (XML namespace). | from [Extension](../../dependencyinjection/extension/extension#method_getNamespace "Symfony\Component\DependencyInjection\Extension\Extension") | | string | [getAlias](#method_getAlias)() Returns the recommended alias to use in XML. | from [Extension](../../dependencyinjection/extension/extension#method_getAlias "Symfony\Component\DependencyInjection\Extension\Extension") | | [ConfigurationInterface](../../config/definition/configurationinterface "Symfony\Component\Config\Definition\ConfigurationInterface")|null | [getConfiguration](#method_getConfiguration)(array $config, [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Returns extension configuration. | from [Extension](../../dependencyinjection/extension/extension#method_getConfiguration "Symfony\Component\DependencyInjection\Extension\Extension") | | | [processConfiguration](#method_processConfiguration)([ConfigurationInterface](../../config/definition/configurationinterface "Symfony\Component\Config\Definition\ConfigurationInterface") $configuration, array $configs) | from [Extension](../../dependencyinjection/extension/extension#method_processConfiguration "Symfony\Component\DependencyInjection\Extension\Extension") | | | [getProcessedConfigs](#method_getProcessedConfigs)() | from [Extension](../../dependencyinjection/extension/extension#method_getProcessedConfigs "Symfony\Component\DependencyInjection\Extension\Extension") | | bool | [isConfigEnabled](#method_isConfigEnabled)([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container, array $config) | from [Extension](../../dependencyinjection/extension/extension#method_isConfigEnabled "Symfony\Component\DependencyInjection\Extension\Extension") | | array | [getAnnotatedClassesToCompile](#method_getAnnotatedClassesToCompile)() Gets the annotated classes to cache. | from [Extension](extension#method_getAnnotatedClassesToCompile "Symfony\Component\HttpKernel\DependencyInjection\Extension") | | | [addAnnotatedClassesToCompile](#method_addAnnotatedClassesToCompile)(array $annotatedClasses) Adds annotated classes to the class cache. | from [Extension](extension#method_addAnnotatedClassesToCompile "Symfony\Component\HttpKernel\DependencyInjection\Extension") | | | [load](#method_load)(array $configs, [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Loads a specific configuration. | | | | [loadInternal](#method_loadInternal)(array $mergedConfig, [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Configures the passed container according to the merged configuration. | | Details ------- ### string getXsdValidationBasePath() Returns the base path for the XSD files. #### Return Value | | | | --- | --- | | string | The XSD base path | ### string getNamespace() Returns the namespace to be used for this extension (XML namespace). #### Return Value | | | | --- | --- | | string | The XML namespace | ### string getAlias() Returns the recommended alias to use in XML. This alias is also the mandatory prefix to use when using YAML. This convention is to remove the "Extension" postfix from the class name and then lowercase and underscore the result. So: ``` AcmeHelloExtension ``` becomes ``` acme_hello ``` This can be overridden in a sub-class to specify the alias manually. #### Return Value | | | | --- | --- | | string | The alias | #### Exceptions | | | | --- | --- | | [BadMethodCallException](../../dependencyinjection/exception/badmethodcallexception "Symfony\Component\DependencyInjection\Exception\BadMethodCallException") | When the extension name does not follow conventions | ### [ConfigurationInterface](../../config/definition/configurationinterface "Symfony\Component\Config\Definition\ConfigurationInterface")|null getConfiguration(array $config, [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Returns extension configuration. #### Parameters | | | | | --- | --- | --- | | array | $config | | | [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | #### Return Value | | | | --- | --- | | [ConfigurationInterface](../../config/definition/configurationinterface "Symfony\Component\Config\Definition\ConfigurationInterface")|null | The configuration or null | ### final protected processConfiguration([ConfigurationInterface](../../config/definition/configurationinterface "Symfony\Component\Config\Definition\ConfigurationInterface") $configuration, array $configs) #### Parameters | | | | | --- | --- | --- | | [ConfigurationInterface](../../config/definition/configurationinterface "Symfony\Component\Config\Definition\ConfigurationInterface") | $configuration | | | array | $configs | | ### final getProcessedConfigs() ### protected bool isConfigEnabled([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container, array $config) #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | | array | $config | | #### Return Value | | | | --- | --- | | bool | Whether the configuration is enabled | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](../../dependencyinjection/exception/invalidargumentexception "Symfony\Component\DependencyInjection\Exception\InvalidArgumentException") | When the config is not enableable | ### array getAnnotatedClassesToCompile() Gets the annotated classes to cache. #### Return Value | | | | --- | --- | | array | An array of classes | ### addAnnotatedClassesToCompile(array $annotatedClasses) Adds annotated classes to the class cache. #### Parameters | | | | | --- | --- | --- | | array | $annotatedClasses | An array of class patterns | ### final load(array $configs, [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Loads a specific configuration. #### Parameters | | | | | --- | --- | --- | | array | $configs | | | [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](http://php.net/InvalidArgumentException) | When provided tag is not defined in this extension | ### abstract protected loadInternal(array $mergedConfig, [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) Configures the passed container according to the merged configuration. #### Parameters | | | | | --- | --- | --- | | array | $mergedConfig | | | [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | symfony FragmentRendererPass FragmentRendererPass ===================== class **FragmentRendererPass** implements [CompilerPassInterface](../../dependencyinjection/compiler/compilerpassinterface "Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface") Adds services tagged kernel.fragment\_renderer as HTTP content rendering strategies. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $handlerService = 'fragment.handler', string $rendererTag = 'kernel.fragment\_renderer') | | | | [process](#method_process)([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) You can modify the container here before it is dumped to PHP code. | | Details ------- ### \_\_construct(string $handlerService = 'fragment.handler', string $rendererTag = 'kernel.fragment\_renderer') #### Parameters | | | | | --- | --- | --- | | string | $handlerService | | | string | $rendererTag | | ### process([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) You can modify the container here before it is dumped to PHP code. #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | symfony ServicesResetter ServicesResetter ================= class **ServicesResetter** Resets provided services. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([Traversable](http://php.net/Traversable) $resettableServices, array $resetMethods) | | | | [reset](#method_reset)() | | Details ------- ### \_\_construct([Traversable](http://php.net/Traversable) $resettableServices, array $resetMethods) #### Parameters | | | | | --- | --- | --- | | [Traversable](http://php.net/Traversable) | $resettableServices | | | array | $resetMethods | | ### reset() symfony LazyLoadingFragmentHandler LazyLoadingFragmentHandler =========================== class **LazyLoadingFragmentHandler** extends [FragmentHandler](../fragment/fragmenthandler "Symfony\Component\HttpKernel\Fragment\FragmentHandler") Lazily loads fragment renderers from the dependency injection container. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(ContainerInterface $container, [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack, bool $debug = false) | | | | [addRenderer](#method_addRenderer)([FragmentRendererInterface](../fragment/fragmentrendererinterface "Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface") $renderer) Adds a renderer. | from [FragmentHandler](../fragment/fragmenthandler#method_addRenderer "Symfony\Component\HttpKernel\Fragment\FragmentHandler") | | string|null | [render](#method_render)(string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $uri, string $renderer = 'inline', array $options = array()) Renders a URI and returns the Response content. | | | string|null | [deliver](#method_deliver)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Delivers the Response as a string. | from [FragmentHandler](../fragment/fragmenthandler#method_deliver "Symfony\Component\HttpKernel\Fragment\FragmentHandler") | Details ------- ### \_\_construct(ContainerInterface $container, [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack, bool $debug = false) #### Parameters | | | | | --- | --- | --- | | ContainerInterface | $container | | | [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") | $requestStack | The Request stack that controls the lifecycle of requests | | bool | $debug | Whether the debug mode is enabled or not | ### addRenderer([FragmentRendererInterface](../fragment/fragmentrendererinterface "Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface") $renderer) Adds a renderer. #### Parameters | | | | | --- | --- | --- | | [FragmentRendererInterface](../fragment/fragmentrendererinterface "Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface") | $renderer | | ### string|null render(string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") $uri, string $renderer = 'inline', array $options = array()) Renders a URI and returns the Response content. Available options: * ignore\_errors: true to return an empty string in case of an error #### Parameters | | | | | --- | --- | --- | | string|[ControllerReference](../controller/controllerreference "Symfony\Component\HttpKernel\Controller\ControllerReference") | $uri | A URI as a string or a ControllerReference instance | | string | $renderer | The renderer name | | array | $options | An array of options | #### Return Value | | | | --- | --- | | string|null | The Response content or null when the Response is streamed | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](http://php.net/InvalidArgumentException) | when the renderer does not exist | | [LogicException](http://php.net/LogicException) | when no master request is being handled | ### protected string|null deliver([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Delivers the Response as a string. When the Response is a StreamedResponse, the content is streamed immediately instead of being returned. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | #### Return Value | | | | --- | --- | | string|null | The Response content or null when the Response is streamed | #### Exceptions | | | | --- | --- | | [RuntimeException](http://php.net/RuntimeException) | when the Response is not successful | symfony MergeExtensionConfigurationPass MergeExtensionConfigurationPass ================================ class **MergeExtensionConfigurationPass** extends [MergeExtensionConfigurationPass](../../dependencyinjection/compiler/mergeextensionconfigurationpass "Symfony\Component\DependencyInjection\Compiler\MergeExtensionConfigurationPass") Ensures certain extensions are always loaded. Methods ------- | | | | | --- | --- | --- | | | [process](#method_process)([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) You can modify the container here before it is dumped to PHP code. | | | | [\_\_construct](#method___construct)(array $extensions) | | Details ------- ### process([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) You can modify the container here before it is dumped to PHP code. #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | ### \_\_construct(array $extensions) #### Parameters | | | | | --- | --- | --- | | array | $extensions | | symfony ResettableServicePass ResettableServicePass ====================== class **ResettableServicePass** implements [CompilerPassInterface](../../dependencyinjection/compiler/compilerpassinterface "Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface") Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $tagName = 'kernel.reset') | | | | [process](#method_process)([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) You can modify the container here before it is dumped to PHP code. | | Details ------- ### \_\_construct(string $tagName = 'kernel.reset') #### Parameters | | | | | --- | --- | --- | | string | $tagName | | ### process([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) You can modify the container here before it is dumped to PHP code. #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | symfony AddAnnotatedClassesToCachePass AddAnnotatedClassesToCachePass =============================== class **AddAnnotatedClassesToCachePass** implements [CompilerPassInterface](../../dependencyinjection/compiler/compilerpassinterface "Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface") Sets the classes to compile in the cache for the container. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([Kernel](../kernel "Symfony\Component\HttpKernel\Kernel") $kernel) | | | | [process](#method_process)([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) You can modify the container here before it is dumped to PHP code. | | Details ------- ### \_\_construct([Kernel](../kernel "Symfony\Component\HttpKernel\Kernel") $kernel) #### Parameters | | | | | --- | --- | --- | | [Kernel](../kernel "Symfony\Component\HttpKernel\Kernel") | $kernel | | ### process([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) You can modify the container here before it is dumped to PHP code. #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | |
programming_docs
symfony RegisterControllerArgumentLocatorsPass RegisterControllerArgumentLocatorsPass ======================================= class **RegisterControllerArgumentLocatorsPass** implements [CompilerPassInterface](../../dependencyinjection/compiler/compilerpassinterface "Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface") Creates the service-locators required by ServiceValueResolver. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $resolverServiceId = 'argument\_resolver.service', string $controllerTag = 'controller.service\_arguments', string $controllerLocator = 'argument\_resolver.controller\_locator') | | | | [process](#method_process)([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) You can modify the container here before it is dumped to PHP code. | | Details ------- ### \_\_construct(string $resolverServiceId = 'argument\_resolver.service', string $controllerTag = 'controller.service\_arguments', string $controllerLocator = 'argument\_resolver.controller\_locator') #### Parameters | | | | | --- | --- | --- | | string | $resolverServiceId | | | string | $controllerTag | | | string | $controllerLocator | | ### process([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) You can modify the container here before it is dumped to PHP code. #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | symfony RemoveEmptyControllerArgumentLocatorsPass RemoveEmptyControllerArgumentLocatorsPass ========================================== class **RemoveEmptyControllerArgumentLocatorsPass** implements [CompilerPassInterface](../../dependencyinjection/compiler/compilerpassinterface "Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface") Removes empty service-locators registered for ServiceValueResolver. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $controllerLocator = 'argument\_resolver.controller\_locator') | | | | [process](#method_process)([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) You can modify the container here before it is dumped to PHP code. | | Details ------- ### \_\_construct(string $controllerLocator = 'argument\_resolver.controller\_locator') #### Parameters | | | | | --- | --- | --- | | string | $controllerLocator | | ### process([ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") $container) You can modify the container here before it is dumped to PHP code. #### Parameters | | | | | --- | --- | --- | | [ContainerBuilder](../../dependencyinjection/containerbuilder "Symfony\Component\DependencyInjection\ContainerBuilder") | $container | | symfony ConflictHttpException ConflictHttpException ====================== class **ConflictHttpException** extends [HttpException](httpexception "Symfony\Component\HttpKernel\Exception\HttpException") Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) | | | int | [getStatusCode](#method_getStatusCode)() Returns the status code. | from [HttpException](httpexception#method_getStatusCode "Symfony\Component\HttpKernel\Exception\HttpException") | | array | [getHeaders](#method_getHeaders)() Returns response headers. | from [HttpException](httpexception#method_getHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | | | [setHeaders](#method_setHeaders)(array $headers) Set response headers. | from [HttpException](httpexception#method_setHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | Details ------- ### \_\_construct(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) #### Parameters | | | | | --- | --- | --- | | string | $message | | | [Exception](http://php.net/Exception) | $previous | | | int|null | $code | | | array | $headers | | ### int getStatusCode() Returns the status code. #### Return Value | | | | --- | --- | | int | An HTTP response status code | ### array getHeaders() Returns response headers. #### Return Value | | | | --- | --- | | array | Response headers | ### setHeaders(array $headers) Set response headers. #### Parameters | | | | | --- | --- | --- | | array | $headers | Response headers | symfony TooManyRequestsHttpException TooManyRequestsHttpException ============================= class **TooManyRequestsHttpException** extends [HttpException](httpexception "Symfony\Component\HttpKernel\Exception\HttpException") Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(int|string $retryAfter = null, string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) | | | int | [getStatusCode](#method_getStatusCode)() Returns the status code. | from [HttpException](httpexception#method_getStatusCode "Symfony\Component\HttpKernel\Exception\HttpException") | | array | [getHeaders](#method_getHeaders)() Returns response headers. | from [HttpException](httpexception#method_getHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | | | [setHeaders](#method_setHeaders)(array $headers) Set response headers. | from [HttpException](httpexception#method_setHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | Details ------- ### \_\_construct(int|string $retryAfter = null, string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) #### Parameters | | | | | --- | --- | --- | | int|string | $retryAfter | The number of seconds or HTTP-date after which the request may be retried | | string | $message | | | [Exception](http://php.net/Exception) | $previous | | | int|null | $code | | | array | $headers | | ### int getStatusCode() Returns the status code. #### Return Value | | | | --- | --- | | int | An HTTP response status code | ### array getHeaders() Returns response headers. #### Return Value | | | | --- | --- | | array | Response headers | ### setHeaders(array $headers) Set response headers. #### Parameters | | | | | --- | --- | --- | | array | $headers | Response headers | symfony PreconditionRequiredHttpException PreconditionRequiredHttpException ================================== class **PreconditionRequiredHttpException** extends [HttpException](httpexception "Symfony\Component\HttpKernel\Exception\HttpException") Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) | | | int | [getStatusCode](#method_getStatusCode)() Returns the status code. | from [HttpException](httpexception#method_getStatusCode "Symfony\Component\HttpKernel\Exception\HttpException") | | array | [getHeaders](#method_getHeaders)() Returns response headers. | from [HttpException](httpexception#method_getHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | | | [setHeaders](#method_setHeaders)(array $headers) Set response headers. | from [HttpException](httpexception#method_setHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | Details ------- ### \_\_construct(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) #### Parameters | | | | | --- | --- | --- | | string | $message | | | [Exception](http://php.net/Exception) | $previous | | | int|null | $code | | | array | $headers | | ### int getStatusCode() Returns the status code. #### Return Value | | | | --- | --- | | int | An HTTP response status code | ### array getHeaders() Returns response headers. #### Return Value | | | | --- | --- | | array | Response headers | ### setHeaders(array $headers) Set response headers. #### Parameters | | | | | --- | --- | --- | | array | $headers | Response headers | symfony ServiceUnavailableHttpException ServiceUnavailableHttpException ================================ class **ServiceUnavailableHttpException** extends [HttpException](httpexception "Symfony\Component\HttpKernel\Exception\HttpException") Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(int|string $retryAfter = null, string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) | | | int | [getStatusCode](#method_getStatusCode)() Returns the status code. | from [HttpException](httpexception#method_getStatusCode "Symfony\Component\HttpKernel\Exception\HttpException") | | array | [getHeaders](#method_getHeaders)() Returns response headers. | from [HttpException](httpexception#method_getHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | | | [setHeaders](#method_setHeaders)(array $headers) Set response headers. | from [HttpException](httpexception#method_setHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | Details ------- ### \_\_construct(int|string $retryAfter = null, string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) #### Parameters | | | | | --- | --- | --- | | int|string | $retryAfter | The number of seconds or HTTP-date after which the request may be retried | | string | $message | | | [Exception](http://php.net/Exception) | $previous | | | int|null | $code | | | array | $headers | | ### int getStatusCode() Returns the status code. #### Return Value | | | | --- | --- | | int | An HTTP response status code | ### array getHeaders() Returns response headers. #### Return Value | | | | --- | --- | | array | Response headers | ### setHeaders(array $headers) Set response headers. #### Parameters | | | | | --- | --- | --- | | array | $headers | Response headers | symfony LengthRequiredHttpException LengthRequiredHttpException ============================ class **LengthRequiredHttpException** extends [HttpException](httpexception "Symfony\Component\HttpKernel\Exception\HttpException") Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) | | | int | [getStatusCode](#method_getStatusCode)() Returns the status code. | from [HttpException](httpexception#method_getStatusCode "Symfony\Component\HttpKernel\Exception\HttpException") | | array | [getHeaders](#method_getHeaders)() Returns response headers. | from [HttpException](httpexception#method_getHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | | | [setHeaders](#method_setHeaders)(array $headers) Set response headers. | from [HttpException](httpexception#method_setHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | Details ------- ### \_\_construct(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) #### Parameters | | | | | --- | --- | --- | | string | $message | | | [Exception](http://php.net/Exception) | $previous | | | int|null | $code | | | array | $headers | | ### int getStatusCode() Returns the status code. #### Return Value | | | | --- | --- | | int | An HTTP response status code | ### array getHeaders() Returns response headers. #### Return Value | | | | --- | --- | | array | Response headers | ### setHeaders(array $headers) Set response headers. #### Parameters | | | | | --- | --- | --- | | array | $headers | Response headers | symfony HttpExceptionInterface HttpExceptionInterface ======================= interface **HttpExceptionInterface** Interface for HTTP error exceptions. Methods ------- | | | | | --- | --- | --- | | int | [getStatusCode](#method_getStatusCode)() Returns the status code. | | | array | [getHeaders](#method_getHeaders)() Returns response headers. | | Details ------- ### int getStatusCode() Returns the status code. #### Return Value | | | | --- | --- | | int | An HTTP response status code | ### array getHeaders() Returns response headers. #### Return Value | | | | --- | --- | | array | Response headers | symfony UnsupportedMediaTypeHttpException UnsupportedMediaTypeHttpException ================================== class **UnsupportedMediaTypeHttpException** extends [HttpException](httpexception "Symfony\Component\HttpKernel\Exception\HttpException") Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) | | | int | [getStatusCode](#method_getStatusCode)() Returns the status code. | from [HttpException](httpexception#method_getStatusCode "Symfony\Component\HttpKernel\Exception\HttpException") | | array | [getHeaders](#method_getHeaders)() Returns response headers. | from [HttpException](httpexception#method_getHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | | | [setHeaders](#method_setHeaders)(array $headers) Set response headers. | from [HttpException](httpexception#method_setHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | Details ------- ### \_\_construct(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) #### Parameters | | | | | --- | --- | --- | | string | $message | | | [Exception](http://php.net/Exception) | $previous | | | int|null | $code | | | array | $headers | | ### int getStatusCode() Returns the status code. #### Return Value | | | | --- | --- | | int | An HTTP response status code | ### array getHeaders() Returns response headers. #### Return Value | | | | --- | --- | | array | Response headers | ### setHeaders(array $headers) Set response headers. #### Parameters | | | | | --- | --- | --- | | array | $headers | Response headers | symfony MethodNotAllowedHttpException MethodNotAllowedHttpException ============================== class **MethodNotAllowedHttpException** extends [HttpException](httpexception "Symfony\Component\HttpKernel\Exception\HttpException") Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(array $allow, string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) | | | int | [getStatusCode](#method_getStatusCode)() Returns the status code. | from [HttpException](httpexception#method_getStatusCode "Symfony\Component\HttpKernel\Exception\HttpException") | | array | [getHeaders](#method_getHeaders)() Returns response headers. | from [HttpException](httpexception#method_getHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | | | [setHeaders](#method_setHeaders)(array $headers) Set response headers. | from [HttpException](httpexception#method_setHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | Details ------- ### \_\_construct(array $allow, string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) #### Parameters | | | | | --- | --- | --- | | array | $allow | An array of allowed methods | | string | $message | | | [Exception](http://php.net/Exception) | $previous | | | int|null | $code | | | array | $headers | | ### int getStatusCode() Returns the status code. #### Return Value | | | | --- | --- | | int | An HTTP response status code | ### array getHeaders() Returns response headers. #### Return Value | | | | --- | --- | | array | Response headers | ### setHeaders(array $headers) Set response headers. #### Parameters | | | | | --- | --- | --- | | array | $headers | Response headers | symfony NotAcceptableHttpException NotAcceptableHttpException =========================== class **NotAcceptableHttpException** extends [HttpException](httpexception "Symfony\Component\HttpKernel\Exception\HttpException") Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) | | | int | [getStatusCode](#method_getStatusCode)() Returns the status code. | from [HttpException](httpexception#method_getStatusCode "Symfony\Component\HttpKernel\Exception\HttpException") | | array | [getHeaders](#method_getHeaders)() Returns response headers. | from [HttpException](httpexception#method_getHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | | | [setHeaders](#method_setHeaders)(array $headers) Set response headers. | from [HttpException](httpexception#method_setHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | Details ------- ### \_\_construct(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) #### Parameters | | | | | --- | --- | --- | | string | $message | | | [Exception](http://php.net/Exception) | $previous | | | int|null | $code | | | array | $headers | | ### int getStatusCode() Returns the status code. #### Return Value | | | | --- | --- | | int | An HTTP response status code | ### array getHeaders() Returns response headers. #### Return Value | | | | --- | --- | | array | Response headers | ### setHeaders(array $headers) Set response headers. #### Parameters | | | | | --- | --- | --- | | array | $headers | Response headers | symfony BadRequestHttpException BadRequestHttpException ======================== class **BadRequestHttpException** extends [HttpException](httpexception "Symfony\Component\HttpKernel\Exception\HttpException") Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) | | | int | [getStatusCode](#method_getStatusCode)() Returns the status code. | from [HttpException](httpexception#method_getStatusCode "Symfony\Component\HttpKernel\Exception\HttpException") | | array | [getHeaders](#method_getHeaders)() Returns response headers. | from [HttpException](httpexception#method_getHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | | | [setHeaders](#method_setHeaders)(array $headers) Set response headers. | from [HttpException](httpexception#method_setHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | Details ------- ### \_\_construct(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) #### Parameters | | | | | --- | --- | --- | | string | $message | | | [Exception](http://php.net/Exception) | $previous | | | int|null | $code | | | array | $headers | | ### int getStatusCode() Returns the status code. #### Return Value | | | | --- | --- | | int | An HTTP response status code | ### array getHeaders() Returns response headers. #### Return Value | | | | --- | --- | | array | Response headers | ### setHeaders(array $headers) Set response headers. #### Parameters | | | | | --- | --- | --- | | array | $headers | Response headers |
programming_docs
symfony AccessDeniedHttpException AccessDeniedHttpException ========================== class **AccessDeniedHttpException** extends [HttpException](httpexception "Symfony\Component\HttpKernel\Exception\HttpException") Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) | | | int | [getStatusCode](#method_getStatusCode)() Returns the status code. | from [HttpException](httpexception#method_getStatusCode "Symfony\Component\HttpKernel\Exception\HttpException") | | array | [getHeaders](#method_getHeaders)() Returns response headers. | from [HttpException](httpexception#method_getHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | | | [setHeaders](#method_setHeaders)(array $headers) Set response headers. | from [HttpException](httpexception#method_setHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | Details ------- ### \_\_construct(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) #### Parameters | | | | | --- | --- | --- | | string | $message | | | [Exception](http://php.net/Exception) | $previous | | | int|null | $code | | | array | $headers | | ### int getStatusCode() Returns the status code. #### Return Value | | | | --- | --- | | int | An HTTP response status code | ### array getHeaders() Returns response headers. #### Return Value | | | | --- | --- | | array | Response headers | ### setHeaders(array $headers) Set response headers. #### Parameters | | | | | --- | --- | --- | | array | $headers | Response headers | symfony PreconditionFailedHttpException PreconditionFailedHttpException ================================ class **PreconditionFailedHttpException** extends [HttpException](httpexception "Symfony\Component\HttpKernel\Exception\HttpException") Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) | | | int | [getStatusCode](#method_getStatusCode)() Returns the status code. | from [HttpException](httpexception#method_getStatusCode "Symfony\Component\HttpKernel\Exception\HttpException") | | array | [getHeaders](#method_getHeaders)() Returns response headers. | from [HttpException](httpexception#method_getHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | | | [setHeaders](#method_setHeaders)(array $headers) Set response headers. | from [HttpException](httpexception#method_setHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | Details ------- ### \_\_construct(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) #### Parameters | | | | | --- | --- | --- | | string | $message | | | [Exception](http://php.net/Exception) | $previous | | | int|null | $code | | | array | $headers | | ### int getStatusCode() Returns the status code. #### Return Value | | | | --- | --- | | int | An HTTP response status code | ### array getHeaders() Returns response headers. #### Return Value | | | | --- | --- | | array | Response headers | ### setHeaders(array $headers) Set response headers. #### Parameters | | | | | --- | --- | --- | | array | $headers | Response headers | symfony UnauthorizedHttpException UnauthorizedHttpException ========================== class **UnauthorizedHttpException** extends [HttpException](httpexception "Symfony\Component\HttpKernel\Exception\HttpException") Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $challenge, string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) | | | int | [getStatusCode](#method_getStatusCode)() Returns the status code. | from [HttpException](httpexception#method_getStatusCode "Symfony\Component\HttpKernel\Exception\HttpException") | | array | [getHeaders](#method_getHeaders)() Returns response headers. | from [HttpException](httpexception#method_getHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | | | [setHeaders](#method_setHeaders)(array $headers) Set response headers. | from [HttpException](httpexception#method_setHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | Details ------- ### \_\_construct(string $challenge, string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) #### Parameters | | | | | --- | --- | --- | | string | $challenge | WWW-Authenticate challenge string | | string | $message | | | [Exception](http://php.net/Exception) | $previous | | | int|null | $code | | | array | $headers | | ### int getStatusCode() Returns the status code. #### Return Value | | | | --- | --- | | int | An HTTP response status code | ### array getHeaders() Returns response headers. #### Return Value | | | | --- | --- | | array | Response headers | ### setHeaders(array $headers) Set response headers. #### Parameters | | | | | --- | --- | --- | | array | $headers | Response headers | symfony UnprocessableEntityHttpException UnprocessableEntityHttpException ================================= class **UnprocessableEntityHttpException** extends [HttpException](httpexception "Symfony\Component\HttpKernel\Exception\HttpException") Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) | | | int | [getStatusCode](#method_getStatusCode)() Returns the status code. | from [HttpException](httpexception#method_getStatusCode "Symfony\Component\HttpKernel\Exception\HttpException") | | array | [getHeaders](#method_getHeaders)() Returns response headers. | from [HttpException](httpexception#method_getHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | | | [setHeaders](#method_setHeaders)(array $headers) Set response headers. | from [HttpException](httpexception#method_setHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | Details ------- ### \_\_construct(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) #### Parameters | | | | | --- | --- | --- | | string | $message | | | [Exception](http://php.net/Exception) | $previous | | | int|null | $code | | | array | $headers | | ### int getStatusCode() Returns the status code. #### Return Value | | | | --- | --- | | int | An HTTP response status code | ### array getHeaders() Returns response headers. #### Return Value | | | | --- | --- | | array | Response headers | ### setHeaders(array $headers) Set response headers. #### Parameters | | | | | --- | --- | --- | | array | $headers | Response headers | symfony HttpException HttpException ============== class **HttpException** extends [RuntimeException](http://php.net/RuntimeException) implements [HttpExceptionInterface](httpexceptioninterface "Symfony\Component\HttpKernel\Exception\HttpExceptionInterface") HttpException. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(int $statusCode, string $message = null, [Exception](http://php.net/Exception) $previous = null, array $headers = array(), int|null $code = 0) | | | int | [getStatusCode](#method_getStatusCode)() Returns the status code. | | | array | [getHeaders](#method_getHeaders)() Returns response headers. | | | | [setHeaders](#method_setHeaders)(array $headers) Set response headers. | | Details ------- ### \_\_construct(int $statusCode, string $message = null, [Exception](http://php.net/Exception) $previous = null, array $headers = array(), int|null $code = 0) #### Parameters | | | | | --- | --- | --- | | int | $statusCode | | | string | $message | | | [Exception](http://php.net/Exception) | $previous | | | array | $headers | | | int|null | $code | | ### int getStatusCode() Returns the status code. #### Return Value | | | | --- | --- | | int | An HTTP response status code | ### array getHeaders() Returns response headers. #### Return Value | | | | --- | --- | | array | Response headers | ### setHeaders(array $headers) Set response headers. #### Parameters | | | | | --- | --- | --- | | array | $headers | Response headers | symfony NotFoundHttpException NotFoundHttpException ====================== class **NotFoundHttpException** extends [HttpException](httpexception "Symfony\Component\HttpKernel\Exception\HttpException") Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) | | | int | [getStatusCode](#method_getStatusCode)() Returns the status code. | from [HttpException](httpexception#method_getStatusCode "Symfony\Component\HttpKernel\Exception\HttpException") | | array | [getHeaders](#method_getHeaders)() Returns response headers. | from [HttpException](httpexception#method_getHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | | | [setHeaders](#method_setHeaders)(array $headers) Set response headers. | from [HttpException](httpexception#method_setHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | Details ------- ### \_\_construct(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) #### Parameters | | | | | --- | --- | --- | | string | $message | | | [Exception](http://php.net/Exception) | $previous | | | int|null | $code | | | array | $headers | | ### int getStatusCode() Returns the status code. #### Return Value | | | | --- | --- | | int | An HTTP response status code | ### array getHeaders() Returns response headers. #### Return Value | | | | --- | --- | | array | Response headers | ### setHeaders(array $headers) Set response headers. #### Parameters | | | | | --- | --- | --- | | array | $headers | Response headers | symfony GoneHttpException GoneHttpException ================== class **GoneHttpException** extends [HttpException](httpexception "Symfony\Component\HttpKernel\Exception\HttpException") Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) | | | int | [getStatusCode](#method_getStatusCode)() Returns the status code. | from [HttpException](httpexception#method_getStatusCode "Symfony\Component\HttpKernel\Exception\HttpException") | | array | [getHeaders](#method_getHeaders)() Returns response headers. | from [HttpException](httpexception#method_getHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | | | [setHeaders](#method_setHeaders)(array $headers) Set response headers. | from [HttpException](httpexception#method_setHeaders "Symfony\Component\HttpKernel\Exception\HttpException") | Details ------- ### \_\_construct(string $message = null, [Exception](http://php.net/Exception) $previous = null, int|null $code = 0, array $headers = array()) #### Parameters | | | | | --- | --- | --- | | string | $message | | | [Exception](http://php.net/Exception) | $previous | | | int|null | $code | | | array | $headers | | ### int getStatusCode() Returns the status code. #### Return Value | | | | --- | --- | | int | An HTTP response status code | ### array getHeaders() Returns response headers. #### Return Value | | | | --- | --- | | array | Response headers | ### setHeaders(array $headers) Set response headers. #### Parameters | | | | | --- | --- | --- | | array | $headers | Response headers | symfony GetResponseForExceptionEvent GetResponseForExceptionEvent ============================= class **GetResponseForExceptionEvent** extends [GetResponseEvent](getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") Allows to create a response for a thrown exception. Call setResponse() to set the response that will be returned for the current request. The propagation of this event is stopped as soon as a response is set. You can also call setException() to replace the thrown exception. This exception will be thrown if no response is set during processing of this event. Methods ------- | | | | | --- | --- | --- | | bool | [isPropagationStopped](#method_isPropagationStopped)() Returns whether further event listeners should be triggered. | from [Event](../../eventdispatcher/event#method_isPropagationStopped "Symfony\Component\EventDispatcher\Event") | | | [stopPropagation](#method_stopPropagation)() Stops the propagation of the event to further event listeners. | from [Event](../../eventdispatcher/event#method_stopPropagation "Symfony\Component\EventDispatcher\Event") | | | [\_\_construct](#method___construct)([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int|null $requestType, [Exception](http://php.net/Exception) $e) | | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | [getKernel](#method_getKernel)() Returns the kernel in which this event was thrown. | from [KernelEvent](kernelevent#method_getKernel "Symfony\Component\HttpKernel\Event\KernelEvent") | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | [getRequest](#method_getRequest)() Returns the request the kernel is currently processing. | from [KernelEvent](kernelevent#method_getRequest "Symfony\Component\HttpKernel\Event\KernelEvent") | | int | [getRequestType](#method_getRequestType)() Returns the request type the kernel is currently processing. | from [KernelEvent](kernelevent#method_getRequestType "Symfony\Component\HttpKernel\Event\KernelEvent") | | bool | [isMasterRequest](#method_isMasterRequest)() Checks if this is a master request. | from [KernelEvent](kernelevent#method_isMasterRequest "Symfony\Component\HttpKernel\Event\KernelEvent") | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response")|null | [getResponse](#method_getResponse)() Returns the response object. | from [GetResponseEvent](getresponseevent#method_getResponse "Symfony\Component\HttpKernel\Event\GetResponseEvent") | | | [setResponse](#method_setResponse)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Sets a response and stops event propagation. | from [GetResponseEvent](getresponseevent#method_setResponse "Symfony\Component\HttpKernel\Event\GetResponseEvent") | | bool | [hasResponse](#method_hasResponse)() Returns whether a response was set. | from [GetResponseEvent](getresponseevent#method_hasResponse "Symfony\Component\HttpKernel\Event\GetResponseEvent") | | [Exception](http://php.net/Exception) | [getException](#method_getException)() Returns the thrown exception. | | | | [setException](#method_setException)([Exception](http://php.net/Exception) $exception) Replaces the thrown exception. | | | | [allowCustomResponseCode](#method_allowCustomResponseCode)() Mark the event as allowing a custom response code. | | | bool | [isAllowingCustomResponseCode](#method_isAllowingCustomResponseCode)() Returns true if the event allows a custom response code. | | Details ------- ### bool isPropagationStopped() Returns whether further event listeners should be triggered. #### Return Value | | | | --- | --- | | bool | Whether propagation was already stopped for this event | #### See also | | | | --- | --- | | [Event::stopPropagation](../../eventdispatcher/event#method_stopPropagation "Symfony\Component\EventDispatcher\Event") | | ### stopPropagation() Stops the propagation of the event to further event listeners. If multiple event listeners are connected to the same event, no further event listener will be triggered once any trigger calls stopPropagation(). ### \_\_construct([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int|null $requestType, [Exception](http://php.net/Exception) $e) #### Parameters | | | | | --- | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | $kernel | The kernel in which this event was thrown | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | The request the kernel is currently processing | | int|null | $requestType | The request type the kernel is currently processing; one of HttpKernelInterface::MASTER\_REQUEST or HttpKernelInterface::SUB\_REQUEST | | [Exception](http://php.net/Exception) | $e | | ### [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") getKernel() Returns the kernel in which this event was thrown. #### Return Value | | | | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | | ### [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") getRequest() Returns the request the kernel is currently processing. #### Return Value | | | | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | | ### int getRequestType() Returns the request type the kernel is currently processing. #### Return Value | | | | --- | --- | | int | One of HttpKernelInterface::MASTER\_REQUEST and HttpKernelInterface::SUB\_REQUEST | ### bool isMasterRequest() Checks if this is a master request. #### Return Value | | | | --- | --- | | bool | True if the request is a master request | ### [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response")|null getResponse() Returns the response object. #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response")|null | | ### setResponse([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Sets a response and stops event propagation. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | ### bool hasResponse() Returns whether a response was set. #### Return Value | | | | --- | --- | | bool | Whether a response was set | ### [Exception](http://php.net/Exception) getException() Returns the thrown exception. #### Return Value | | | | --- | --- | | [Exception](http://php.net/Exception) | The thrown exception | ### setException([Exception](http://php.net/Exception) $exception) Replaces the thrown exception. This exception will be thrown if no response is set in the event. #### Parameters | | | | | --- | --- | --- | | [Exception](http://php.net/Exception) | $exception | The thrown exception | ### allowCustomResponseCode() Mark the event as allowing a custom response code. ### bool isAllowingCustomResponseCode() Returns true if the event allows a custom response code. #### Return Value | | | | --- | --- | | bool | |
programming_docs
symfony FinishRequestEvent FinishRequestEvent =================== class **FinishRequestEvent** extends [KernelEvent](kernelevent "Symfony\Component\HttpKernel\Event\KernelEvent") Triggered whenever a request is fully processed. Methods ------- | | | | | --- | --- | --- | | bool | [isPropagationStopped](#method_isPropagationStopped)() Returns whether further event listeners should be triggered. | from [Event](../../eventdispatcher/event#method_isPropagationStopped "Symfony\Component\EventDispatcher\Event") | | | [stopPropagation](#method_stopPropagation)() Stops the propagation of the event to further event listeners. | from [Event](../../eventdispatcher/event#method_stopPropagation "Symfony\Component\EventDispatcher\Event") | | | [\_\_construct](#method___construct)([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int|null $requestType) | from [KernelEvent](kernelevent#method___construct "Symfony\Component\HttpKernel\Event\KernelEvent") | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | [getKernel](#method_getKernel)() Returns the kernel in which this event was thrown. | from [KernelEvent](kernelevent#method_getKernel "Symfony\Component\HttpKernel\Event\KernelEvent") | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | [getRequest](#method_getRequest)() Returns the request the kernel is currently processing. | from [KernelEvent](kernelevent#method_getRequest "Symfony\Component\HttpKernel\Event\KernelEvent") | | int | [getRequestType](#method_getRequestType)() Returns the request type the kernel is currently processing. | from [KernelEvent](kernelevent#method_getRequestType "Symfony\Component\HttpKernel\Event\KernelEvent") | | bool | [isMasterRequest](#method_isMasterRequest)() Checks if this is a master request. | from [KernelEvent](kernelevent#method_isMasterRequest "Symfony\Component\HttpKernel\Event\KernelEvent") | Details ------- ### bool isPropagationStopped() Returns whether further event listeners should be triggered. #### Return Value | | | | --- | --- | | bool | Whether propagation was already stopped for this event | #### See also | | | | --- | --- | | [Event::stopPropagation](../../eventdispatcher/event#method_stopPropagation "Symfony\Component\EventDispatcher\Event") | | ### stopPropagation() Stops the propagation of the event to further event listeners. If multiple event listeners are connected to the same event, no further event listener will be triggered once any trigger calls stopPropagation(). ### \_\_construct([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int|null $requestType) #### Parameters | | | | | --- | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | $kernel | The kernel in which this event was thrown | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | The request the kernel is currently processing | | int|null | $requestType | The request type the kernel is currently processing; one of HttpKernelInterface::MASTER\_REQUEST or HttpKernelInterface::SUB\_REQUEST | ### [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") getKernel() Returns the kernel in which this event was thrown. #### Return Value | | | | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | | ### [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") getRequest() Returns the request the kernel is currently processing. #### Return Value | | | | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | | ### int getRequestType() Returns the request type the kernel is currently processing. #### Return Value | | | | --- | --- | | int | One of HttpKernelInterface::MASTER\_REQUEST and HttpKernelInterface::SUB\_REQUEST | ### bool isMasterRequest() Checks if this is a master request. #### Return Value | | | | --- | --- | | bool | True if the request is a master request | symfony GetResponseEvent GetResponseEvent ================= class **GetResponseEvent** extends [KernelEvent](kernelevent "Symfony\Component\HttpKernel\Event\KernelEvent") Allows to create a response for a request. Call setResponse() to set the response that will be returned for the current request. The propagation of this event is stopped as soon as a response is set. Methods ------- | | | | | --- | --- | --- | | bool | [isPropagationStopped](#method_isPropagationStopped)() Returns whether further event listeners should be triggered. | from [Event](../../eventdispatcher/event#method_isPropagationStopped "Symfony\Component\EventDispatcher\Event") | | | [stopPropagation](#method_stopPropagation)() Stops the propagation of the event to further event listeners. | from [Event](../../eventdispatcher/event#method_stopPropagation "Symfony\Component\EventDispatcher\Event") | | | [\_\_construct](#method___construct)([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int|null $requestType) | from [KernelEvent](kernelevent#method___construct "Symfony\Component\HttpKernel\Event\KernelEvent") | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | [getKernel](#method_getKernel)() Returns the kernel in which this event was thrown. | from [KernelEvent](kernelevent#method_getKernel "Symfony\Component\HttpKernel\Event\KernelEvent") | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | [getRequest](#method_getRequest)() Returns the request the kernel is currently processing. | from [KernelEvent](kernelevent#method_getRequest "Symfony\Component\HttpKernel\Event\KernelEvent") | | int | [getRequestType](#method_getRequestType)() Returns the request type the kernel is currently processing. | from [KernelEvent](kernelevent#method_getRequestType "Symfony\Component\HttpKernel\Event\KernelEvent") | | bool | [isMasterRequest](#method_isMasterRequest)() Checks if this is a master request. | from [KernelEvent](kernelevent#method_isMasterRequest "Symfony\Component\HttpKernel\Event\KernelEvent") | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response")|null | [getResponse](#method_getResponse)() Returns the response object. | | | | [setResponse](#method_setResponse)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Sets a response and stops event propagation. | | | bool | [hasResponse](#method_hasResponse)() Returns whether a response was set. | | Details ------- ### bool isPropagationStopped() Returns whether further event listeners should be triggered. #### Return Value | | | | --- | --- | | bool | Whether propagation was already stopped for this event | #### See also | | | | --- | --- | | [Event::stopPropagation](../../eventdispatcher/event#method_stopPropagation "Symfony\Component\EventDispatcher\Event") | | ### stopPropagation() Stops the propagation of the event to further event listeners. If multiple event listeners are connected to the same event, no further event listener will be triggered once any trigger calls stopPropagation(). ### \_\_construct([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int|null $requestType) #### Parameters | | | | | --- | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | $kernel | The kernel in which this event was thrown | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | The request the kernel is currently processing | | int|null | $requestType | The request type the kernel is currently processing; one of HttpKernelInterface::MASTER\_REQUEST or HttpKernelInterface::SUB\_REQUEST | ### [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") getKernel() Returns the kernel in which this event was thrown. #### Return Value | | | | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | | ### [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") getRequest() Returns the request the kernel is currently processing. #### Return Value | | | | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | | ### int getRequestType() Returns the request type the kernel is currently processing. #### Return Value | | | | --- | --- | | int | One of HttpKernelInterface::MASTER\_REQUEST and HttpKernelInterface::SUB\_REQUEST | ### bool isMasterRequest() Checks if this is a master request. #### Return Value | | | | --- | --- | | bool | True if the request is a master request | ### [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response")|null getResponse() Returns the response object. #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response")|null | | ### setResponse([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Sets a response and stops event propagation. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | ### bool hasResponse() Returns whether a response was set. #### Return Value | | | | --- | --- | | bool | Whether a response was set | symfony KernelEvent KernelEvent ============ class **KernelEvent** extends [Event](../../eventdispatcher/event "Symfony\Component\EventDispatcher\Event") Base class for events thrown in the HttpKernel component. Methods ------- | | | | | --- | --- | --- | | bool | [isPropagationStopped](#method_isPropagationStopped)() Returns whether further event listeners should be triggered. | from [Event](../../eventdispatcher/event#method_isPropagationStopped "Symfony\Component\EventDispatcher\Event") | | | [stopPropagation](#method_stopPropagation)() Stops the propagation of the event to further event listeners. | from [Event](../../eventdispatcher/event#method_stopPropagation "Symfony\Component\EventDispatcher\Event") | | | [\_\_construct](#method___construct)([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int|null $requestType) | | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | [getKernel](#method_getKernel)() Returns the kernel in which this event was thrown. | | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | [getRequest](#method_getRequest)() Returns the request the kernel is currently processing. | | | int | [getRequestType](#method_getRequestType)() Returns the request type the kernel is currently processing. | | | bool | [isMasterRequest](#method_isMasterRequest)() Checks if this is a master request. | | Details ------- ### bool isPropagationStopped() Returns whether further event listeners should be triggered. #### Return Value | | | | --- | --- | | bool | Whether propagation was already stopped for this event | #### See also | | | | --- | --- | | [Event::stopPropagation](../../eventdispatcher/event#method_stopPropagation "Symfony\Component\EventDispatcher\Event") | | ### stopPropagation() Stops the propagation of the event to further event listeners. If multiple event listeners are connected to the same event, no further event listener will be triggered once any trigger calls stopPropagation(). ### \_\_construct([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int|null $requestType) #### Parameters | | | | | --- | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | $kernel | The kernel in which this event was thrown | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | The request the kernel is currently processing | | int|null | $requestType | The request type the kernel is currently processing; one of HttpKernelInterface::MASTER\_REQUEST or HttpKernelInterface::SUB\_REQUEST | ### [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") getKernel() Returns the kernel in which this event was thrown. #### Return Value | | | | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | | ### [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") getRequest() Returns the request the kernel is currently processing. #### Return Value | | | | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | | ### int getRequestType() Returns the request type the kernel is currently processing. #### Return Value | | | | --- | --- | | int | One of HttpKernelInterface::MASTER\_REQUEST and HttpKernelInterface::SUB\_REQUEST | ### bool isMasterRequest() Checks if this is a master request. #### Return Value | | | | --- | --- | | bool | True if the request is a master request | symfony GetResponseForControllerResultEvent GetResponseForControllerResultEvent ==================================== class **GetResponseForControllerResultEvent** extends [GetResponseEvent](getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") Allows to create a response for the return value of a controller. Call setResponse() to set the response that will be returned for the current request. The propagation of this event is stopped as soon as a response is set. Methods ------- | | | | | --- | --- | --- | | bool | [isPropagationStopped](#method_isPropagationStopped)() Returns whether further event listeners should be triggered. | from [Event](../../eventdispatcher/event#method_isPropagationStopped "Symfony\Component\EventDispatcher\Event") | | | [stopPropagation](#method_stopPropagation)() Stops the propagation of the event to further event listeners. | from [Event](../../eventdispatcher/event#method_stopPropagation "Symfony\Component\EventDispatcher\Event") | | | [\_\_construct](#method___construct)([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int|null $requestType, $controllerResult) | | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | [getKernel](#method_getKernel)() Returns the kernel in which this event was thrown. | from [KernelEvent](kernelevent#method_getKernel "Symfony\Component\HttpKernel\Event\KernelEvent") | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | [getRequest](#method_getRequest)() Returns the request the kernel is currently processing. | from [KernelEvent](kernelevent#method_getRequest "Symfony\Component\HttpKernel\Event\KernelEvent") | | int | [getRequestType](#method_getRequestType)() Returns the request type the kernel is currently processing. | from [KernelEvent](kernelevent#method_getRequestType "Symfony\Component\HttpKernel\Event\KernelEvent") | | bool | [isMasterRequest](#method_isMasterRequest)() Checks if this is a master request. | from [KernelEvent](kernelevent#method_isMasterRequest "Symfony\Component\HttpKernel\Event\KernelEvent") | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response")|null | [getResponse](#method_getResponse)() Returns the response object. | from [GetResponseEvent](getresponseevent#method_getResponse "Symfony\Component\HttpKernel\Event\GetResponseEvent") | | | [setResponse](#method_setResponse)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Sets a response and stops event propagation. | from [GetResponseEvent](getresponseevent#method_setResponse "Symfony\Component\HttpKernel\Event\GetResponseEvent") | | bool | [hasResponse](#method_hasResponse)() Returns whether a response was set. | from [GetResponseEvent](getresponseevent#method_hasResponse "Symfony\Component\HttpKernel\Event\GetResponseEvent") | | mixed | [getControllerResult](#method_getControllerResult)() Returns the return value of the controller. | | | | [setControllerResult](#method_setControllerResult)(mixed $controllerResult) Assigns the return value of the controller. | | Details ------- ### bool isPropagationStopped() Returns whether further event listeners should be triggered. #### Return Value | | | | --- | --- | | bool | Whether propagation was already stopped for this event | #### See also | | | | --- | --- | | [Event::stopPropagation](../../eventdispatcher/event#method_stopPropagation "Symfony\Component\EventDispatcher\Event") | | ### stopPropagation() Stops the propagation of the event to further event listeners. If multiple event listeners are connected to the same event, no further event listener will be triggered once any trigger calls stopPropagation(). ### \_\_construct([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int|null $requestType, $controllerResult) #### Parameters | | | | | --- | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | $kernel | The kernel in which this event was thrown | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | The request the kernel is currently processing | | int|null | $requestType | The request type the kernel is currently processing; one of HttpKernelInterface::MASTER\_REQUEST or HttpKernelInterface::SUB\_REQUEST | | | $controllerResult | | ### [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") getKernel() Returns the kernel in which this event was thrown. #### Return Value | | | | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | | ### [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") getRequest() Returns the request the kernel is currently processing. #### Return Value | | | | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | | ### int getRequestType() Returns the request type the kernel is currently processing. #### Return Value | | | | --- | --- | | int | One of HttpKernelInterface::MASTER\_REQUEST and HttpKernelInterface::SUB\_REQUEST | ### bool isMasterRequest() Checks if this is a master request. #### Return Value | | | | --- | --- | | bool | True if the request is a master request | ### [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response")|null getResponse() Returns the response object. #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response")|null | | ### setResponse([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Sets a response and stops event propagation. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | ### bool hasResponse() Returns whether a response was set. #### Return Value | | | | --- | --- | | bool | Whether a response was set | ### mixed getControllerResult() Returns the return value of the controller. #### Return Value | | | | --- | --- | | mixed | The controller return value | ### setControllerResult(mixed $controllerResult) Assigns the return value of the controller. #### Parameters | | | | | --- | --- | --- | | mixed | $controllerResult | The controller return value |
programming_docs
symfony FilterControllerArgumentsEvent FilterControllerArgumentsEvent =============================== class **FilterControllerArgumentsEvent** extends [FilterControllerEvent](filtercontrollerevent "Symfony\Component\HttpKernel\Event\FilterControllerEvent") Allows filtering of controller arguments. You can call getController() to retrieve the controller and getArguments to retrieve the current arguments. With setArguments() you can replace arguments that are used to call the controller. Arguments set in the event must be compatible with the signature of the controller. Methods ------- | | | | | --- | --- | --- | | bool | [isPropagationStopped](#method_isPropagationStopped)() Returns whether further event listeners should be triggered. | from [Event](../../eventdispatcher/event#method_isPropagationStopped "Symfony\Component\EventDispatcher\Event") | | | [stopPropagation](#method_stopPropagation)() Stops the propagation of the event to further event listeners. | from [Event](../../eventdispatcher/event#method_stopPropagation "Symfony\Component\EventDispatcher\Event") | | | [\_\_construct](#method___construct)([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, callable $controller, array $arguments, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int|null $requestType) | | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | [getKernel](#method_getKernel)() Returns the kernel in which this event was thrown. | from [KernelEvent](kernelevent#method_getKernel "Symfony\Component\HttpKernel\Event\KernelEvent") | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | [getRequest](#method_getRequest)() Returns the request the kernel is currently processing. | from [KernelEvent](kernelevent#method_getRequest "Symfony\Component\HttpKernel\Event\KernelEvent") | | int | [getRequestType](#method_getRequestType)() Returns the request type the kernel is currently processing. | from [KernelEvent](kernelevent#method_getRequestType "Symfony\Component\HttpKernel\Event\KernelEvent") | | bool | [isMasterRequest](#method_isMasterRequest)() Checks if this is a master request. | from [KernelEvent](kernelevent#method_isMasterRequest "Symfony\Component\HttpKernel\Event\KernelEvent") | | callable | [getController](#method_getController)() Returns the current controller. | from [FilterControllerEvent](filtercontrollerevent#method_getController "Symfony\Component\HttpKernel\Event\FilterControllerEvent") | | | [setController](#method_setController)(callable $controller) | from [FilterControllerEvent](filtercontrollerevent#method_setController "Symfony\Component\HttpKernel\Event\FilterControllerEvent") | | array | [getArguments](#method_getArguments)() | | | | [setArguments](#method_setArguments)(array $arguments) | | Details ------- ### bool isPropagationStopped() Returns whether further event listeners should be triggered. #### Return Value | | | | --- | --- | | bool | Whether propagation was already stopped for this event | #### See also | | | | --- | --- | | [Event::stopPropagation](../../eventdispatcher/event#method_stopPropagation "Symfony\Component\EventDispatcher\Event") | | ### stopPropagation() Stops the propagation of the event to further event listeners. If multiple event listeners are connected to the same event, no further event listener will be triggered once any trigger calls stopPropagation(). ### \_\_construct([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, callable $controller, array $arguments, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int|null $requestType) #### Parameters | | | | | --- | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | $kernel | The kernel in which this event was thrown | | callable | $controller | | | array | $arguments | | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | The request the kernel is currently processing | | int|null | $requestType | The request type the kernel is currently processing; one of HttpKernelInterface::MASTER\_REQUEST or HttpKernelInterface::SUB\_REQUEST | ### [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") getKernel() Returns the kernel in which this event was thrown. #### Return Value | | | | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | | ### [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") getRequest() Returns the request the kernel is currently processing. #### Return Value | | | | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | | ### int getRequestType() Returns the request type the kernel is currently processing. #### Return Value | | | | --- | --- | | int | One of HttpKernelInterface::MASTER\_REQUEST and HttpKernelInterface::SUB\_REQUEST | ### bool isMasterRequest() Checks if this is a master request. #### Return Value | | | | --- | --- | | bool | True if the request is a master request | ### callable getController() Returns the current controller. #### Return Value | | | | --- | --- | | callable | | ### setController(callable $controller) #### Parameters | | | | | --- | --- | --- | | callable | $controller | | ### array getArguments() #### Return Value | | | | --- | --- | | array | | ### setArguments(array $arguments) #### Parameters | | | | | --- | --- | --- | | array | $arguments | | symfony PostResponseEvent PostResponseEvent ================== class **PostResponseEvent** extends [KernelEvent](kernelevent "Symfony\Component\HttpKernel\Event\KernelEvent") Allows to execute logic after a response was sent. Since it's only triggered on master requests, the `getRequestType()` method will always return the value of `HttpKernelInterface::MASTER_REQUEST`. Methods ------- | | | | | --- | --- | --- | | bool | [isPropagationStopped](#method_isPropagationStopped)() Returns whether further event listeners should be triggered. | from [Event](../../eventdispatcher/event#method_isPropagationStopped "Symfony\Component\EventDispatcher\Event") | | | [stopPropagation](#method_stopPropagation)() Stops the propagation of the event to further event listeners. | from [Event](../../eventdispatcher/event#method_stopPropagation "Symfony\Component\EventDispatcher\Event") | | | [\_\_construct](#method___construct)([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) | | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | [getKernel](#method_getKernel)() Returns the kernel in which this event was thrown. | from [KernelEvent](kernelevent#method_getKernel "Symfony\Component\HttpKernel\Event\KernelEvent") | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | [getRequest](#method_getRequest)() Returns the request the kernel is currently processing. | from [KernelEvent](kernelevent#method_getRequest "Symfony\Component\HttpKernel\Event\KernelEvent") | | int | [getRequestType](#method_getRequestType)() Returns the request type the kernel is currently processing. | from [KernelEvent](kernelevent#method_getRequestType "Symfony\Component\HttpKernel\Event\KernelEvent") | | bool | [isMasterRequest](#method_isMasterRequest)() Checks if this is a master request. | from [KernelEvent](kernelevent#method_isMasterRequest "Symfony\Component\HttpKernel\Event\KernelEvent") | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [getResponse](#method_getResponse)() Returns the response for which this event was thrown. | | Details ------- ### bool isPropagationStopped() Returns whether further event listeners should be triggered. #### Return Value | | | | --- | --- | | bool | Whether propagation was already stopped for this event | #### See also | | | | --- | --- | | [Event::stopPropagation](../../eventdispatcher/event#method_stopPropagation "Symfony\Component\EventDispatcher\Event") | | ### stopPropagation() Stops the propagation of the event to further event listeners. If multiple event listeners are connected to the same event, no further event listener will be triggered once any trigger calls stopPropagation(). ### \_\_construct([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) #### Parameters | | | | | --- | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | $kernel | The kernel in which this event was thrown | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | The request the kernel is currently processing | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | ### [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") getKernel() Returns the kernel in which this event was thrown. #### Return Value | | | | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | | ### [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") getRequest() Returns the request the kernel is currently processing. #### Return Value | | | | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | | ### int getRequestType() Returns the request type the kernel is currently processing. #### Return Value | | | | --- | --- | | int | One of HttpKernelInterface::MASTER\_REQUEST and HttpKernelInterface::SUB\_REQUEST | ### bool isMasterRequest() Checks if this is a master request. #### Return Value | | | | --- | --- | | bool | True if the request is a master request | ### [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") getResponse() Returns the response for which this event was thrown. #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | | symfony FilterResponseEvent FilterResponseEvent ==================== class **FilterResponseEvent** extends [KernelEvent](kernelevent "Symfony\Component\HttpKernel\Event\KernelEvent") Allows to filter a Response object. You can call getResponse() to retrieve the current response. With setResponse() you can set a new response that will be returned to the browser. Methods ------- | | | | | --- | --- | --- | | bool | [isPropagationStopped](#method_isPropagationStopped)() Returns whether further event listeners should be triggered. | from [Event](../../eventdispatcher/event#method_isPropagationStopped "Symfony\Component\EventDispatcher\Event") | | | [stopPropagation](#method_stopPropagation)() Stops the propagation of the event to further event listeners. | from [Event](../../eventdispatcher/event#method_stopPropagation "Symfony\Component\EventDispatcher\Event") | | | [\_\_construct](#method___construct)([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int|null $requestType, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) | | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | [getKernel](#method_getKernel)() Returns the kernel in which this event was thrown. | from [KernelEvent](kernelevent#method_getKernel "Symfony\Component\HttpKernel\Event\KernelEvent") | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | [getRequest](#method_getRequest)() Returns the request the kernel is currently processing. | from [KernelEvent](kernelevent#method_getRequest "Symfony\Component\HttpKernel\Event\KernelEvent") | | int | [getRequestType](#method_getRequestType)() Returns the request type the kernel is currently processing. | from [KernelEvent](kernelevent#method_getRequestType "Symfony\Component\HttpKernel\Event\KernelEvent") | | bool | [isMasterRequest](#method_isMasterRequest)() Checks if this is a master request. | from [KernelEvent](kernelevent#method_isMasterRequest "Symfony\Component\HttpKernel\Event\KernelEvent") | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | [getResponse](#method_getResponse)() Returns the current response object. | | | | [setResponse](#method_setResponse)([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Sets a new response object. | | Details ------- ### bool isPropagationStopped() Returns whether further event listeners should be triggered. #### Return Value | | | | --- | --- | | bool | Whether propagation was already stopped for this event | #### See also | | | | --- | --- | | [Event::stopPropagation](../../eventdispatcher/event#method_stopPropagation "Symfony\Component\EventDispatcher\Event") | | ### stopPropagation() Stops the propagation of the event to further event listeners. If multiple event listeners are connected to the same event, no further event listener will be triggered once any trigger calls stopPropagation(). ### \_\_construct([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int|null $requestType, [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) #### Parameters | | | | | --- | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | $kernel | The kernel in which this event was thrown | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | The request the kernel is currently processing | | int|null | $requestType | The request type the kernel is currently processing; one of HttpKernelInterface::MASTER\_REQUEST or HttpKernelInterface::SUB\_REQUEST | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | ### [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") getKernel() Returns the kernel in which this event was thrown. #### Return Value | | | | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | | ### [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") getRequest() Returns the request the kernel is currently processing. #### Return Value | | | | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | | ### int getRequestType() Returns the request type the kernel is currently processing. #### Return Value | | | | --- | --- | | int | One of HttpKernelInterface::MASTER\_REQUEST and HttpKernelInterface::SUB\_REQUEST | ### bool isMasterRequest() Checks if this is a master request. #### Return Value | | | | --- | --- | | bool | True if the request is a master request | ### [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") getResponse() Returns the current response object. #### Return Value | | | | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | | ### setResponse([Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") $response) Sets a new response object. #### Parameters | | | | | --- | --- | --- | | [Response](../../httpfoundation/response "Symfony\Component\HttpFoundation\Response") | $response | | symfony FilterControllerEvent FilterControllerEvent ====================== class **FilterControllerEvent** extends [KernelEvent](kernelevent "Symfony\Component\HttpKernel\Event\KernelEvent") Allows filtering of a controller callable. You can call getController() to retrieve the current controller. With setController() you can set a new controller that is used in the processing of the request. Controllers should be callables. Methods ------- | | | | | --- | --- | --- | | bool | [isPropagationStopped](#method_isPropagationStopped)() Returns whether further event listeners should be triggered. | from [Event](../../eventdispatcher/event#method_isPropagationStopped "Symfony\Component\EventDispatcher\Event") | | | [stopPropagation](#method_stopPropagation)() Stops the propagation of the event to further event listeners. | from [Event](../../eventdispatcher/event#method_stopPropagation "Symfony\Component\EventDispatcher\Event") | | | [\_\_construct](#method___construct)([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, callable $controller, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int|null $requestType) | | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | [getKernel](#method_getKernel)() Returns the kernel in which this event was thrown. | from [KernelEvent](kernelevent#method_getKernel "Symfony\Component\HttpKernel\Event\KernelEvent") | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | [getRequest](#method_getRequest)() Returns the request the kernel is currently processing. | from [KernelEvent](kernelevent#method_getRequest "Symfony\Component\HttpKernel\Event\KernelEvent") | | int | [getRequestType](#method_getRequestType)() Returns the request type the kernel is currently processing. | from [KernelEvent](kernelevent#method_getRequestType "Symfony\Component\HttpKernel\Event\KernelEvent") | | bool | [isMasterRequest](#method_isMasterRequest)() Checks if this is a master request. | from [KernelEvent](kernelevent#method_isMasterRequest "Symfony\Component\HttpKernel\Event\KernelEvent") | | callable | [getController](#method_getController)() Returns the current controller. | | | | [setController](#method_setController)(callable $controller) | | Details ------- ### bool isPropagationStopped() Returns whether further event listeners should be triggered. #### Return Value | | | | --- | --- | | bool | Whether propagation was already stopped for this event | #### See also | | | | --- | --- | | [Event::stopPropagation](../../eventdispatcher/event#method_stopPropagation "Symfony\Component\EventDispatcher\Event") | | ### stopPropagation() Stops the propagation of the event to further event listeners. If multiple event listeners are connected to the same event, no further event listener will be triggered once any trigger calls stopPropagation(). ### \_\_construct([HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") $kernel, callable $controller, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request, int|null $requestType) #### Parameters | | | | | --- | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | $kernel | The kernel in which this event was thrown | | callable | $controller | | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | The request the kernel is currently processing | | int|null | $requestType | The request type the kernel is currently processing; one of HttpKernelInterface::MASTER\_REQUEST or HttpKernelInterface::SUB\_REQUEST | ### [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") getKernel() Returns the kernel in which this event was thrown. #### Return Value | | | | --- | --- | | [HttpKernelInterface](../httpkernelinterface "Symfony\Component\HttpKernel\HttpKernelInterface") | | ### [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") getRequest() Returns the request the kernel is currently processing. #### Return Value | | | | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | | ### int getRequestType() Returns the request type the kernel is currently processing. #### Return Value | | | | --- | --- | | int | One of HttpKernelInterface::MASTER\_REQUEST and HttpKernelInterface::SUB\_REQUEST | ### bool isMasterRequest() Checks if this is a master request. #### Return Value | | | | --- | --- | | bool | True if the request is a master request | ### callable getController() Returns the current controller. #### Return Value | | | | --- | --- | | callable | | ### setController(callable $controller) #### Parameters | | | | | --- | --- | --- | | callable | $controller | |
programming_docs
symfony FileLinkFormatter FileLinkFormatter ================== class **FileLinkFormatter** implements [Serializable](http://php.net/Serializable) Formats debug file links. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)($fileLinkFormat = null, [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack = null, string $baseDir = null, $urlFormat = null) | | | | [format](#method_format)($file, $line) | | | | [serialize](#method_serialize)() | | | | [unserialize](#method_unserialize)($serialized) | | | static | [generateUrlFormat](#method_generateUrlFormat)([UrlGeneratorInterface](../../routing/generator/urlgeneratorinterface "Symfony\Component\Routing\Generator\UrlGeneratorInterface") $router, $routeName, $queryString) | | Details ------- ### \_\_construct($fileLinkFormat = null, [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack = null, string $baseDir = null, $urlFormat = null) #### Parameters | | | | | --- | --- | --- | | | $fileLinkFormat | | | [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") | $requestStack | | | string | $baseDir | | | | $urlFormat | | ### format($file, $line) #### Parameters | | | | | --- | --- | --- | | | $file | | | | $line | | ### serialize() ### unserialize($serialized) #### Parameters | | | | | --- | --- | --- | | | $serialized | | ### static generateUrlFormat([UrlGeneratorInterface](../../routing/generator/urlgeneratorinterface "Symfony\Component\Routing\Generator\UrlGeneratorInterface") $router, $routeName, $queryString) #### Parameters | | | | | --- | --- | --- | | [UrlGeneratorInterface](../../routing/generator/urlgeneratorinterface "Symfony\Component\Routing\Generator\UrlGeneratorInterface") | $router | | | | $routeName | | | | $queryString | | symfony TraceableEventDispatcher TraceableEventDispatcher ========================= class **TraceableEventDispatcher** extends [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") Collects some data about event listeners. This event dispatcher delegates the dispatching to another one. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $logger | | from [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher#property_logger "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | | protected | $stopwatch | | from [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher#property_stopwatch "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([EventDispatcherInterface](../../eventdispatcher/eventdispatcherinterface "Symfony\Component\EventDispatcher\EventDispatcherInterface") $dispatcher, [Stopwatch](../../stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") $stopwatch, LoggerInterface $logger = null) | from [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher#method___construct "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | | | [addListener](#method_addListener)(string $eventName, callable $listener, int $priority = 0) Adds an event listener that listens on the specified events. | from [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher#method_addListener "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | | | [addSubscriber](#method_addSubscriber)([EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") $subscriber) Adds an event subscriber. | from [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher#method_addSubscriber "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | | | [removeListener](#method_removeListener)(string $eventName, callable $listener) Removes an event listener from the specified events. | from [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher#method_removeListener "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | | | [removeSubscriber](#method_removeSubscriber)([EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") $subscriber) | from [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher#method_removeSubscriber "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | | array | [getListeners](#method_getListeners)(string $eventName = null) Gets the listeners of a specific event or all listeners sorted by descending priority. | from [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher#method_getListeners "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | | int|null | [getListenerPriority](#method_getListenerPriority)(string $eventName, callable $listener) Gets the listener priority for a specific event. | from [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher#method_getListenerPriority "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | | bool | [hasListeners](#method_hasListeners)(string $eventName = null) Checks whether an event has any registered listeners. | from [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher#method_hasListeners "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | | [Event](../../eventdispatcher/event "Symfony\Component\EventDispatcher\Event") | [dispatch](#method_dispatch)(string $eventName, [Event](../../eventdispatcher/event "Symfony\Component\EventDispatcher\Event") $event = null) Dispatches an event to all registered listeners. | from [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher#method_dispatch "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | | array | [getCalledListeners](#method_getCalledListeners)() Gets the called listeners. | from [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher#method_getCalledListeners "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | | array | [getNotCalledListeners](#method_getNotCalledListeners)() Gets the not called listeners. | from [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher#method_getNotCalledListeners "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | | array | [getOrphanedEvents](#method_getOrphanedEvents)() | from [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher#method_getOrphanedEvents "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | | | [reset](#method_reset)() Resets the trace. | from [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher#method_reset "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | | mixed | [\_\_call](#method___call)(string $method, array $arguments) Proxies all method calls to the original event dispatcher. | from [TraceableEventDispatcher](../../eventdispatcher/debug/traceableeventdispatcher#method___call "Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher") | | | [preDispatch](#method_preDispatch)(string $eventName, [Event](../../eventdispatcher/event "Symfony\Component\EventDispatcher\Event") $event) Called before dispatching the event. | | | | [postDispatch](#method_postDispatch)(string $eventName, [Event](../../eventdispatcher/event "Symfony\Component\EventDispatcher\Event") $event) Called after dispatching the event. | | Details ------- ### \_\_construct([EventDispatcherInterface](../../eventdispatcher/eventdispatcherinterface "Symfony\Component\EventDispatcher\EventDispatcherInterface") $dispatcher, [Stopwatch](../../stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") $stopwatch, LoggerInterface $logger = null) #### Parameters | | | | | --- | --- | --- | | [EventDispatcherInterface](../../eventdispatcher/eventdispatcherinterface "Symfony\Component\EventDispatcher\EventDispatcherInterface") | $dispatcher | | | [Stopwatch](../../stopwatch/stopwatch "Symfony\Component\Stopwatch\Stopwatch") | $stopwatch | | | LoggerInterface | $logger | | ### addListener(string $eventName, callable $listener, int $priority = 0) Adds an event listener that listens on the specified events. #### Parameters | | | | | --- | --- | --- | | string | $eventName | The event to listen on | | callable | $listener | The listener | | int | $priority | The higher this value, the earlier an event listener will be triggered in the chain (defaults to 0) | ### addSubscriber([EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") $subscriber) Adds an event subscriber. The subscriber is asked for all the events he is interested in and added as a listener for these events. #### Parameters | | | | | --- | --- | --- | | [EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") | $subscriber | | ### removeListener(string $eventName, callable $listener) Removes an event listener from the specified events. #### Parameters | | | | | --- | --- | --- | | string | $eventName | The event to remove a listener from | | callable | $listener | The listener to remove | ### removeSubscriber([EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") $subscriber) #### Parameters | | | | | --- | --- | --- | | [EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") | $subscriber | | ### array getListeners(string $eventName = null) Gets the listeners of a specific event or all listeners sorted by descending priority. #### Parameters | | | | | --- | --- | --- | | string | $eventName | The name of the event | #### Return Value | | | | --- | --- | | array | The event listeners for the specified event, or all event listeners by event name | ### int|null getListenerPriority(string $eventName, callable $listener) Gets the listener priority for a specific event. Returns null if the event or the listener does not exist. #### Parameters | | | | | --- | --- | --- | | string | $eventName | The name of the event | | callable | $listener | The listener | #### Return Value | | | | --- | --- | | int|null | The event listener priority | ### bool hasListeners(string $eventName = null) Checks whether an event has any registered listeners. #### Parameters | | | | | --- | --- | --- | | string | $eventName | The name of the event | #### Return Value | | | | --- | --- | | bool | true if the specified event has any listeners, false otherwise | ### [Event](../../eventdispatcher/event "Symfony\Component\EventDispatcher\Event") dispatch(string $eventName, [Event](../../eventdispatcher/event "Symfony\Component\EventDispatcher\Event") $event = null) Dispatches an event to all registered listeners. #### Parameters | | | | | --- | --- | --- | | string | $eventName | The name of the event to dispatch. The name of the event is the name of the method that is invoked on listeners. | | [Event](../../eventdispatcher/event "Symfony\Component\EventDispatcher\Event") | $event | The event to pass to the event handlers/listeners If not supplied, an empty Event instance is created | #### Return Value | | | | --- | --- | | [Event](../../eventdispatcher/event "Symfony\Component\EventDispatcher\Event") | | ### array getCalledListeners() Gets the called listeners. #### Return Value | | | | --- | --- | | array | An array of called listeners | ### array getNotCalledListeners() Gets the not called listeners. #### Return Value | | | | --- | --- | | array | An array of not called listeners | ### array getOrphanedEvents() #### Return Value | | | | --- | --- | | array | | ### reset() Resets the trace. ### mixed \_\_call(string $method, array $arguments) Proxies all method calls to the original event dispatcher. #### Parameters | | | | | --- | --- | --- | | string | $method | The method name | | array | $arguments | The method arguments | #### Return Value | | | | --- | --- | | mixed | | ### protected preDispatch(string $eventName, [Event](../../eventdispatcher/event "Symfony\Component\EventDispatcher\Event") $event) Called before dispatching the event. #### Parameters | | | | | --- | --- | --- | | string | $eventName | The event name | | [Event](../../eventdispatcher/event "Symfony\Component\EventDispatcher\Event") | $event | The event | ### protected postDispatch(string $eventName, [Event](../../eventdispatcher/event "Symfony\Component\EventDispatcher\Event") $event) Called after dispatching the event. #### Parameters | | | | | --- | --- | --- | | string | $eventName | The event name | | [Event](../../eventdispatcher/event "Symfony\Component\EventDispatcher\Event") | $event | The event | symfony ProfilerListener ProfilerListener ================= class **ProfilerListener** implements [EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") ProfilerListener collects data for the current request by listening to the kernel events. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $profiler | | | | protected | $matcher | | | | protected | $onlyException | | | | protected | $onlyMasterRequests | | | | protected | $exception | | | | protected | $profiles | | | | protected | $requestStack | | | | protected | $parents | | | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([Profiler](../profiler/profiler "Symfony\Component\HttpKernel\Profiler\Profiler") $profiler, [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack, [RequestMatcherInterface](../../httpfoundation/requestmatcherinterface "Symfony\Component\HttpFoundation\RequestMatcherInterface") $matcher = null, bool $onlyException = false, bool $onlyMasterRequests = false) | | | | [onKernelException](#method_onKernelException)([GetResponseForExceptionEvent](../event/getresponseforexceptionevent "Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent") $event) Handles the onKernelException event. | | | | [onKernelResponse](#method_onKernelResponse)([FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) Handles the onKernelResponse event. | | | | [onKernelTerminate](#method_onKernelTerminate)([PostResponseEvent](../event/postresponseevent "Symfony\Component\HttpKernel\Event\PostResponseEvent") $event) | | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | | Details ------- ### \_\_construct([Profiler](../profiler/profiler "Symfony\Component\HttpKernel\Profiler\Profiler") $profiler, [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack, [RequestMatcherInterface](../../httpfoundation/requestmatcherinterface "Symfony\Component\HttpFoundation\RequestMatcherInterface") $matcher = null, bool $onlyException = false, bool $onlyMasterRequests = false) #### Parameters | | | | | --- | --- | --- | | [Profiler](../profiler/profiler "Symfony\Component\HttpKernel\Profiler\Profiler") | $profiler | A Profiler instance | | [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") | $requestStack | A RequestStack instance | | [RequestMatcherInterface](../../httpfoundation/requestmatcherinterface "Symfony\Component\HttpFoundation\RequestMatcherInterface") | $matcher | A RequestMatcher instance | | bool | $onlyException | True if the profiler only collects data when an exception occurs, false otherwise | | bool | $onlyMasterRequests | True if the profiler only collects data when the request is a master request, false otherwise | ### onKernelException([GetResponseForExceptionEvent](../event/getresponseforexceptionevent "Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent") $event) Handles the onKernelException event. #### Parameters | | | | | --- | --- | --- | | [GetResponseForExceptionEvent](../event/getresponseforexceptionevent "Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent") | $event | | ### onKernelResponse([FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) Handles the onKernelResponse event. #### Parameters | | | | | --- | --- | --- | | [FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") | $event | | ### onKernelTerminate([PostResponseEvent](../event/postresponseevent "Symfony\Component\HttpKernel\Event\PostResponseEvent") $event) #### Parameters | | | | | --- | --- | --- | | [PostResponseEvent](../event/postresponseevent "Symfony\Component\HttpKernel\Event\PostResponseEvent") | $event | | ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to | symfony StreamedResponseListener StreamedResponseListener ========================= class **StreamedResponseListener** implements [EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") StreamedResponseListener is responsible for sending the Response to the client. Methods ------- | | | | | --- | --- | --- | | | [onKernelResponse](#method_onKernelResponse)([FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) Filters the Response. | | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | | Details ------- ### onKernelResponse([FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) Filters the Response. #### Parameters | | | | | --- | --- | --- | | [FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") | $event | | ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to |
programming_docs
symfony SessionListener SessionListener ================ class **SessionListener** extends [AbstractSessionListener](abstractsessionlistener "Symfony\Component\HttpKernel\EventListener\AbstractSessionListener") Sets the session in the request. Constants --------- | | | | --- | --- | | NO\_AUTO\_CACHE\_CONTROL\_HEADER | | Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $container | | from [AbstractSessionListener](abstractsessionlistener#property_container "Symfony\Component\HttpKernel\EventListener\AbstractSessionListener") | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(ContainerInterface $container) | | | | [onKernelRequest](#method_onKernelRequest)([GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) | from [AbstractSessionListener](abstractsessionlistener#method_onKernelRequest "Symfony\Component\HttpKernel\EventListener\AbstractSessionListener") | | | [onKernelResponse](#method_onKernelResponse)([FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) | from [AbstractSessionListener](abstractsessionlistener#method_onKernelResponse "Symfony\Component\HttpKernel\EventListener\AbstractSessionListener") | | | [onFinishRequest](#method_onFinishRequest)([FinishRequestEvent](../event/finishrequestevent "Symfony\Component\HttpKernel\Event\FinishRequestEvent") $event) | from [AbstractSessionListener](abstractsessionlistener#method_onFinishRequest "Symfony\Component\HttpKernel\EventListener\AbstractSessionListener") | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | from [AbstractSessionListener](abstractsessionlistener#method_getSubscribedEvents "Symfony\Component\HttpKernel\EventListener\AbstractSessionListener") | | [SessionInterface](../../httpfoundation/session/sessioninterface "Symfony\Component\HttpFoundation\Session\SessionInterface")|null | [getSession](#method_getSession)() Gets the session object. | | Details ------- ### \_\_construct(ContainerInterface $container) #### Parameters | | | | | --- | --- | --- | | ContainerInterface | $container | | ### onKernelRequest([GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) #### Parameters | | | | | --- | --- | --- | | [GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") | $event | | ### onKernelResponse([FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) #### Parameters | | | | | --- | --- | --- | | [FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") | $event | | ### onFinishRequest([FinishRequestEvent](../event/finishrequestevent "Symfony\Component\HttpKernel\Event\FinishRequestEvent") $event) #### Parameters | | | | | --- | --- | --- | | [FinishRequestEvent](../event/finishrequestevent "Symfony\Component\HttpKernel\Event\FinishRequestEvent") | $event | | ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to | ### protected [SessionInterface](../../httpfoundation/session/sessioninterface "Symfony\Component\HttpFoundation\Session\SessionInterface")|null getSession() Gets the session object. #### Return Value | | | | --- | --- | | [SessionInterface](../../httpfoundation/session/sessioninterface "Symfony\Component\HttpFoundation\Session\SessionInterface")|null | A SessionInterface instance or null if no session is available | symfony AddRequestFormatsListener AddRequestFormatsListener ========================== class **AddRequestFormatsListener** implements [EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") Adds configured formats to each request. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $formats | | | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(array $formats) | | | | [onKernelRequest](#method_onKernelRequest)([GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) Adds request formats. | | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | | Details ------- ### \_\_construct(array $formats) #### Parameters | | | | | --- | --- | --- | | array | $formats | | ### onKernelRequest([GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) Adds request formats. #### Parameters | | | | | --- | --- | --- | | [GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") | $event | | ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to | symfony AbstractTestSessionListener AbstractTestSessionListener ============================ abstract class **AbstractTestSessionListener** implements [EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") TestSessionListener. Saves session in test environment. Methods ------- | | | | | --- | --- | --- | | | [onKernelRequest](#method_onKernelRequest)([GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) | | | | [onKernelResponse](#method_onKernelResponse)([FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) Checks if session was initialized and saves if current request is master Runs on 'kernel.response' in test environment. | | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | | | [SessionInterface](../../httpfoundation/session/sessioninterface "Symfony\Component\HttpFoundation\Session\SessionInterface")|null | [getSession](#method_getSession)() Gets the session object. | | Details ------- ### onKernelRequest([GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) #### Parameters | | | | | --- | --- | --- | | [GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") | $event | | ### onKernelResponse([FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) Checks if session was initialized and saves if current request is master Runs on 'kernel.response' in test environment. #### Parameters | | | | | --- | --- | --- | | [FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") | $event | | ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to | ### abstract protected [SessionInterface](../../httpfoundation/session/sessioninterface "Symfony\Component\HttpFoundation\Session\SessionInterface")|null getSession() Gets the session object. #### Return Value | | | | --- | --- | | [SessionInterface](../../httpfoundation/session/sessioninterface "Symfony\Component\HttpFoundation\Session\SessionInterface")|null | A SessionInterface instance or null if no session is available | symfony RouterListener RouterListener =============== class **RouterListener** implements [EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") Initializes the context from the request and sets request attributes based on a matching route. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([UrlMatcherInterface](../../routing/matcher/urlmatcherinterface "Symfony\Component\Routing\Matcher\UrlMatcherInterface")|[RequestMatcherInterface](../../routing/matcher/requestmatcherinterface "Symfony\Component\Routing\Matcher\RequestMatcherInterface") $matcher, [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack, [RequestContext](../../routing/requestcontext "Symfony\Component\Routing\RequestContext") $context = null, LoggerInterface $logger = null, string $projectDir = null, bool $debug = true) | | | | [onKernelFinishRequest](#method_onKernelFinishRequest)([FinishRequestEvent](../event/finishrequestevent "Symfony\Component\HttpKernel\Event\FinishRequestEvent") $event) After a sub-request is done, we need to reset the routing context to the parent request so that the URL generator operates on the correct context again. | | | | [onKernelRequest](#method_onKernelRequest)([GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) | | | | [onKernelException](#method_onKernelException)([GetResponseForExceptionEvent](../event/getresponseforexceptionevent "Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent") $event) | | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | | Details ------- ### \_\_construct([UrlMatcherInterface](../../routing/matcher/urlmatcherinterface "Symfony\Component\Routing\Matcher\UrlMatcherInterface")|[RequestMatcherInterface](../../routing/matcher/requestmatcherinterface "Symfony\Component\Routing\Matcher\RequestMatcherInterface") $matcher, [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack, [RequestContext](../../routing/requestcontext "Symfony\Component\Routing\RequestContext") $context = null, LoggerInterface $logger = null, string $projectDir = null, bool $debug = true) #### Parameters | | | | | --- | --- | --- | | [UrlMatcherInterface](../../routing/matcher/urlmatcherinterface "Symfony\Component\Routing\Matcher\UrlMatcherInterface")|[RequestMatcherInterface](../../routing/matcher/requestmatcherinterface "Symfony\Component\Routing\Matcher\RequestMatcherInterface") | $matcher | The Url or Request matcher | | [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") | $requestStack | A RequestStack instance | | [RequestContext](../../routing/requestcontext "Symfony\Component\Routing\RequestContext") | $context | The RequestContext (can be null when $matcher implements RequestContextAwareInterface) | | LoggerInterface | $logger | The logger | | string | $projectDir | | | bool | $debug | | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](http://php.net/InvalidArgumentException) | | ### onKernelFinishRequest([FinishRequestEvent](../event/finishrequestevent "Symfony\Component\HttpKernel\Event\FinishRequestEvent") $event) After a sub-request is done, we need to reset the routing context to the parent request so that the URL generator operates on the correct context again. #### Parameters | | | | | --- | --- | --- | | [FinishRequestEvent](../event/finishrequestevent "Symfony\Component\HttpKernel\Event\FinishRequestEvent") | $event | | ### onKernelRequest([GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) #### Parameters | | | | | --- | --- | --- | | [GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") | $event | | ### onKernelException([GetResponseForExceptionEvent](../event/getresponseforexceptionevent "Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent") $event) #### Parameters | | | | | --- | --- | --- | | [GetResponseForExceptionEvent](../event/getresponseforexceptionevent "Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent") | $event | | ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to | symfony DumpListener DumpListener ============= class **DumpListener** implements [EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") Configures dump() handler. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([ClonerInterface](../../vardumper/cloner/clonerinterface "Symfony\Component\VarDumper\Cloner\ClonerInterface") $cloner, [DataDumperInterface](../../vardumper/dumper/datadumperinterface "Symfony\Component\VarDumper\Dumper\DataDumperInterface") $dumper, [Connection](../../vardumper/server/connection "Symfony\Component\VarDumper\Server\Connection") $connection = null) | | | | [configure](#method_configure)() | | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | | Details ------- ### \_\_construct([ClonerInterface](../../vardumper/cloner/clonerinterface "Symfony\Component\VarDumper\Cloner\ClonerInterface") $cloner, [DataDumperInterface](../../vardumper/dumper/datadumperinterface "Symfony\Component\VarDumper\Dumper\DataDumperInterface") $dumper, [Connection](../../vardumper/server/connection "Symfony\Component\VarDumper\Server\Connection") $connection = null) #### Parameters | | | | | --- | --- | --- | | [ClonerInterface](../../vardumper/cloner/clonerinterface "Symfony\Component\VarDumper\Cloner\ClonerInterface") | $cloner | | | [DataDumperInterface](../../vardumper/dumper/datadumperinterface "Symfony\Component\VarDumper\Dumper\DataDumperInterface") | $dumper | | | [Connection](../../vardumper/server/connection "Symfony\Component\VarDumper\Server\Connection") | $connection | | ### configure() ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to | symfony ValidateRequestListener ValidateRequestListener ======================== class **ValidateRequestListener** implements [EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") Validates Requests. Methods ------- | | | | | --- | --- | --- | | | [onKernelRequest](#method_onKernelRequest)([GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) Performs the validation. | | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | | Details ------- ### onKernelRequest([GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) Performs the validation. #### Parameters | | | | | --- | --- | --- | | [GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") | $event | | ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to | symfony ResponseListener ResponseListener ================= class **ResponseListener** implements [EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") ResponseListener fixes the Response headers based on the Request. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(string $charset) | | | | [onKernelResponse](#method_onKernelResponse)([FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) Filters the Response. | | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | | Details ------- ### \_\_construct(string $charset) #### Parameters | | | | | --- | --- | --- | | string | $charset | | ### onKernelResponse([FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) Filters the Response. #### Parameters | | | | | --- | --- | --- | | [FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") | $event | | ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to |
programming_docs
symfony LocaleListener LocaleListener =============== class **LocaleListener** implements [EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") Initializes the locale based on the current request. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack, string $defaultLocale = 'en', [RequestContextAwareInterface](../../routing/requestcontextawareinterface "Symfony\Component\Routing\RequestContextAwareInterface") $router = null) | | | | [onKernelRequest](#method_onKernelRequest)([GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) | | | | [onKernelFinishRequest](#method_onKernelFinishRequest)([FinishRequestEvent](../event/finishrequestevent "Symfony\Component\HttpKernel\Event\FinishRequestEvent") $event) | | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | | Details ------- ### \_\_construct([RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack, string $defaultLocale = 'en', [RequestContextAwareInterface](../../routing/requestcontextawareinterface "Symfony\Component\Routing\RequestContextAwareInterface") $router = null) #### Parameters | | | | | --- | --- | --- | | [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") | $requestStack | A RequestStack instance | | string | $defaultLocale | The default locale | | [RequestContextAwareInterface](../../routing/requestcontextawareinterface "Symfony\Component\Routing\RequestContextAwareInterface") | $router | The router | ### onKernelRequest([GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) #### Parameters | | | | | --- | --- | --- | | [GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") | $event | | ### onKernelFinishRequest([FinishRequestEvent](../event/finishrequestevent "Symfony\Component\HttpKernel\Event\FinishRequestEvent") $event) #### Parameters | | | | | --- | --- | --- | | [FinishRequestEvent](../event/finishrequestevent "Symfony\Component\HttpKernel\Event\FinishRequestEvent") | $event | | ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to | symfony TestSessionListener TestSessionListener ==================== class **TestSessionListener** extends [AbstractTestSessionListener](abstracttestsessionlistener "Symfony\Component\HttpKernel\EventListener\AbstractTestSessionListener") Sets the session in the request. Methods ------- | | | | | --- | --- | --- | | | [onKernelRequest](#method_onKernelRequest)([GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) | from [AbstractTestSessionListener](abstracttestsessionlistener#method_onKernelRequest "Symfony\Component\HttpKernel\EventListener\AbstractTestSessionListener") | | | [onKernelResponse](#method_onKernelResponse)([FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) Checks if session was initialized and saves if current request is master Runs on 'kernel.response' in test environment. | from [AbstractTestSessionListener](abstracttestsessionlistener#method_onKernelResponse "Symfony\Component\HttpKernel\EventListener\AbstractTestSessionListener") | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | from [AbstractTestSessionListener](abstracttestsessionlistener#method_getSubscribedEvents "Symfony\Component\HttpKernel\EventListener\AbstractTestSessionListener") | | [SessionInterface](../../httpfoundation/session/sessioninterface "Symfony\Component\HttpFoundation\Session\SessionInterface")|null | [getSession](#method_getSession)() Gets the session object. | | | | [\_\_construct](#method___construct)(ContainerInterface $container) | | Details ------- ### onKernelRequest([GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) #### Parameters | | | | | --- | --- | --- | | [GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") | $event | | ### onKernelResponse([FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) Checks if session was initialized and saves if current request is master Runs on 'kernel.response' in test environment. #### Parameters | | | | | --- | --- | --- | | [FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") | $event | | ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to | ### protected [SessionInterface](../../httpfoundation/session/sessioninterface "Symfony\Component\HttpFoundation\Session\SessionInterface")|null getSession() Gets the session object. #### Return Value | | | | --- | --- | | [SessionInterface](../../httpfoundation/session/sessioninterface "Symfony\Component\HttpFoundation\Session\SessionInterface")|null | A SessionInterface instance or null if no session is available | ### \_\_construct(ContainerInterface $container) #### Parameters | | | | | --- | --- | --- | | ContainerInterface | $container | | symfony SurrogateListener SurrogateListener ================== class **SurrogateListener** implements [EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") SurrogateListener adds a Surrogate-Control HTTP header when the Response needs to be parsed for Surrogates. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([SurrogateInterface](../httpcache/surrogateinterface "Symfony\Component\HttpKernel\HttpCache\SurrogateInterface") $surrogate = null) | | | | [onKernelResponse](#method_onKernelResponse)([FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) Filters the Response. | | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | | Details ------- ### \_\_construct([SurrogateInterface](../httpcache/surrogateinterface "Symfony\Component\HttpKernel\HttpCache\SurrogateInterface") $surrogate = null) #### Parameters | | | | | --- | --- | --- | | [SurrogateInterface](../httpcache/surrogateinterface "Symfony\Component\HttpKernel\HttpCache\SurrogateInterface") | $surrogate | | ### onKernelResponse([FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) Filters the Response. #### Parameters | | | | | --- | --- | --- | | [FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") | $event | | ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to | symfony ExceptionListener ExceptionListener ================== class **ExceptionListener** implements [EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") ExceptionListener. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $controller | | | | protected | $logger | | | | protected | $debug | | | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)($controller, LoggerInterface $logger = null, $debug = false) | | | | [logKernelException](#method_logKernelException)([GetResponseForExceptionEvent](../event/getresponseforexceptionevent "Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent") $event) | | | | [onKernelException](#method_onKernelException)([GetResponseForExceptionEvent](../event/getresponseforexceptionevent "Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent") $event) | | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | | | | [logException](#method_logException)([Exception](http://php.net/Exception) $exception, string $message) Logs an exception. | | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | [duplicateRequest](#method_duplicateRequest)([Exception](http://php.net/Exception) $exception, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Clones the request for the exception. | | Details ------- ### \_\_construct($controller, LoggerInterface $logger = null, $debug = false) #### Parameters | | | | | --- | --- | --- | | | $controller | | | LoggerInterface | $logger | | | | $debug | | ### logKernelException([GetResponseForExceptionEvent](../event/getresponseforexceptionevent "Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent") $event) #### Parameters | | | | | --- | --- | --- | | [GetResponseForExceptionEvent](../event/getresponseforexceptionevent "Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent") | $event | | ### onKernelException([GetResponseForExceptionEvent](../event/getresponseforexceptionevent "Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent") $event) #### Parameters | | | | | --- | --- | --- | | [GetResponseForExceptionEvent](../event/getresponseforexceptionevent "Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent") | $event | | ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to | ### protected logException([Exception](http://php.net/Exception) $exception, string $message) Logs an exception. #### Parameters | | | | | --- | --- | --- | | [Exception](http://php.net/Exception) | $exception | The \Exception instance | | string | $message | The error message to log | ### protected [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") duplicateRequest([Exception](http://php.net/Exception) $exception, [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) Clones the request for the exception. #### Parameters | | | | | --- | --- | --- | | [Exception](http://php.net/Exception) | $exception | The thrown exception | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | The original request | #### Return Value | | | | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request The cloned request | symfony TranslatorListener TranslatorListener =================== class **TranslatorListener** implements [EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") Synchronizes the locale between the request and the translator. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([TranslatorInterface](../../translation/translatorinterface "Symfony\Component\Translation\TranslatorInterface") $translator, [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack) | | | | [onKernelRequest](#method_onKernelRequest)([GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) | | | | [onKernelFinishRequest](#method_onKernelFinishRequest)([FinishRequestEvent](../event/finishrequestevent "Symfony\Component\HttpKernel\Event\FinishRequestEvent") $event) | | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | | Details ------- ### \_\_construct([TranslatorInterface](../../translation/translatorinterface "Symfony\Component\Translation\TranslatorInterface") $translator, [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") $requestStack) #### Parameters | | | | | --- | --- | --- | | [TranslatorInterface](../../translation/translatorinterface "Symfony\Component\Translation\TranslatorInterface") | $translator | | | [RequestStack](../../httpfoundation/requeststack "Symfony\Component\HttpFoundation\RequestStack") | $requestStack | | ### onKernelRequest([GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) #### Parameters | | | | | --- | --- | --- | | [GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") | $event | | ### onKernelFinishRequest([FinishRequestEvent](../event/finishrequestevent "Symfony\Component\HttpKernel\Event\FinishRequestEvent") $event) #### Parameters | | | | | --- | --- | --- | | [FinishRequestEvent](../event/finishrequestevent "Symfony\Component\HttpKernel\Event\FinishRequestEvent") | $event | | ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to | symfony DebugHandlersListener DebugHandlersListener ====================== class **DebugHandlersListener** implements [EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") Configures errors and exceptions handlers. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(callable $exceptionHandler = null, LoggerInterface $logger = null, array|int $levels = E\_ALL, int|null $throwAt = E\_ALL, bool $scream = true, string|array $fileLinkFormat = null, bool $scope = true) | | | | [configure](#method_configure)([Event](../../eventdispatcher/event "Symfony\Component\EventDispatcher\Event") $event = null) Configures the error handler. | | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | | Details ------- ### \_\_construct(callable $exceptionHandler = null, LoggerInterface $logger = null, array|int $levels = E\_ALL, int|null $throwAt = E\_ALL, bool $scream = true, string|array $fileLinkFormat = null, bool $scope = true) #### Parameters | | | | | --- | --- | --- | | callable | $exceptionHandler | A handler that will be called on Exception | | LoggerInterface | $logger | A PSR-3 logger | | array|int | $levels | An array map of E\_\* to LogLevel::\* or an integer bit field of E\_\* constants | | int|null | $throwAt | Thrown errors in a bit field of E\_\* constants, or null to keep the current value | | bool | $scream | Enables/disables screaming mode, where even silenced errors are logged | | string|array | $fileLinkFormat | The format for links to source files | | bool | $scope | Enables/disables scoping mode | ### configure([Event](../../eventdispatcher/event "Symfony\Component\EventDispatcher\Event") $event = null) Configures the error handler. #### Parameters | | | | | --- | --- | --- | | [Event](../../eventdispatcher/event "Symfony\Component\EventDispatcher\Event") | $event | | ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to | symfony FragmentListener FragmentListener ================= class **FragmentListener** implements [EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") Handles content fragments represented by special URIs. All URL paths starting with /\_fragment are handled as content fragments by this listener. If throws an AccessDeniedHttpException exception if the request is not signed or if it is not an internal sub-request. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([UriSigner](../urisigner "Symfony\Component\HttpKernel\UriSigner") $signer, string $fragmentPath = '/\_fragment') | | | | [onKernelRequest](#method_onKernelRequest)([GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) Fixes request attributes when the path is '/\_fragment'. | | | | [validateRequest](#method_validateRequest)([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) | | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | | Details ------- ### \_\_construct([UriSigner](../urisigner "Symfony\Component\HttpKernel\UriSigner") $signer, string $fragmentPath = '/\_fragment') #### Parameters | | | | | --- | --- | --- | | [UriSigner](../urisigner "Symfony\Component\HttpKernel\UriSigner") | $signer | A UriSigner instance | | string | $fragmentPath | The path that triggers this listener | ### onKernelRequest([GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) Fixes request attributes when the path is '/\_fragment'. #### Parameters | | | | | --- | --- | --- | | [GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") | $event | | #### Exceptions | | | | --- | --- | | [AccessDeniedHttpException](../exception/accessdeniedhttpexception "Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException") | if the request does not come from a trusted IP | ### protected validateRequest([Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") $request) #### Parameters | | | | | --- | --- | --- | | [Request](../../httpfoundation/request "Symfony\Component\HttpFoundation\Request") | $request | | ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to |
programming_docs
symfony SaveSessionListener deprecated SaveSessionListener deprecated =============================== class **SaveSessionListener** implements [EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") deprecated | since | Symfony 4.1, use AbstractSessionListener instead | Methods ------- | | | | | --- | --- | --- | | | [onKernelResponse](#method_onKernelResponse)([FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) | | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | | Details ------- ### onKernelResponse([FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) #### Parameters | | | | | --- | --- | --- | | [FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") | $event | | ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to | symfony AbstractSessionListener AbstractSessionListener ======================== abstract class **AbstractSessionListener** implements [EventSubscriberInterface](../../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") Sets the session onto the request on the "kernel.request" event and saves it on the "kernel.response" event. In addition, if the session has been started it overrides the Cache-Control header in such a way that all caching is disabled in that case. If you have a scenario where caching responses with session information in them makes sense, you can disable this behaviour by setting the header AbstractSessionListener::NO\_AUTO\_CACHE\_CONTROL\_HEADER on the response. Constants --------- | | | | --- | --- | | NO\_AUTO\_CACHE\_CONTROL\_HEADER | | Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $container | | | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)(ContainerInterface $container = null) | | | | [onKernelRequest](#method_onKernelRequest)([GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) | | | | [onKernelResponse](#method_onKernelResponse)([FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) | | | | [onFinishRequest](#method_onFinishRequest)([FinishRequestEvent](../event/finishrequestevent "Symfony\Component\HttpKernel\Event\FinishRequestEvent") $event) | | | static array | [getSubscribedEvents](#method_getSubscribedEvents)() Returns an array of event names this subscriber wants to listen to. | | | [SessionInterface](../../httpfoundation/session/sessioninterface "Symfony\Component\HttpFoundation\Session\SessionInterface")|null | [getSession](#method_getSession)() Gets the session object. | | Details ------- ### \_\_construct(ContainerInterface $container = null) #### Parameters | | | | | --- | --- | --- | | ContainerInterface | $container | | ### onKernelRequest([GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") $event) #### Parameters | | | | | --- | --- | --- | | [GetResponseEvent](../event/getresponseevent "Symfony\Component\HttpKernel\Event\GetResponseEvent") | $event | | ### onKernelResponse([FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") $event) #### Parameters | | | | | --- | --- | --- | | [FilterResponseEvent](../event/filterresponseevent "Symfony\Component\HttpKernel\Event\FilterResponseEvent") | $event | | ### onFinishRequest([FinishRequestEvent](../event/finishrequestevent "Symfony\Component\HttpKernel\Event\FinishRequestEvent") $event) #### Parameters | | | | | --- | --- | --- | | [FinishRequestEvent](../event/finishrequestevent "Symfony\Component\HttpKernel\Event\FinishRequestEvent") | $event | | ### static array getSubscribedEvents() Returns an array of event names this subscriber wants to listen to. The array keys are event names and the value can be: * The method name to call (priority defaults to 0) * An array composed of the method name to call and the priority * An array of arrays composed of the method names to call and respective priorities, or 0 if unset For instance: * array('eventName' => 'methodName') * array('eventName' => array('methodName', $priority)) * array('eventName' => array(array('methodName1', $priority), array('methodName2'))) #### Return Value | | | | --- | --- | | array | The event names to listen to | ### abstract protected [SessionInterface](../../httpfoundation/session/sessioninterface "Symfony\Component\HttpFoundation\Session\SessionInterface")|null getSession() Gets the session object. #### Return Value | | | | --- | --- | | [SessionInterface](../../httpfoundation/session/sessioninterface "Symfony\Component\HttpFoundation\Session\SessionInterface")|null | A SessionInterface instance or null if no session is available | symfony RequestHandlerInterface RequestHandlerInterface ======================== interface **RequestHandlerInterface** Submits forms if they were submitted. Methods ------- | | | | | --- | --- | --- | | | [handleRequest](#method_handleRequest)([FormInterface](forminterface "Symfony\Component\Form\FormInterface") $form, mixed $request = null) Submits a form if it was submitted. | | | bool | [isFileUpload](#method_isFileUpload)(mixed $data) Returns true if the given data is a file upload. | | Details ------- ### handleRequest([FormInterface](forminterface "Symfony\Component\Form\FormInterface") $form, mixed $request = null) Submits a form if it was submitted. #### Parameters | | | | | --- | --- | --- | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | $form | The form to submit | | mixed | $request | The current request | ### bool isFileUpload(mixed $data) Returns true if the given data is a file upload. #### Parameters | | | | | --- | --- | --- | | mixed | $data | The form field data | #### Return Value | | | | --- | --- | | bool | | symfony AbstractType AbstractType ============= abstract class **AbstractType** implements [FormTypeInterface](formtypeinterface "Symfony\Component\Form\FormTypeInterface") Methods ------- | | | | | --- | --- | --- | | | [buildForm](#method_buildForm)([FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") $builder, array $options) Builds the form. | | | | [buildView](#method_buildView)([FormView](formview "Symfony\Component\Form\FormView") $view, [FormInterface](forminterface "Symfony\Component\Form\FormInterface") $form, array $options) Builds the form view. | | | | [finishView](#method_finishView)([FormView](formview "Symfony\Component\Form\FormView") $view, [FormInterface](forminterface "Symfony\Component\Form\FormInterface") $form, array $options) Finishes the form view. | | | | [configureOptions](#method_configureOptions)([OptionsResolver](../optionsresolver/optionsresolver "Symfony\Component\OptionsResolver\OptionsResolver") $resolver) Configures the options for this type. | | | string | [getBlockPrefix](#method_getBlockPrefix)() Returns the prefix of the template block name for this type. | | | string|null | [getParent](#method_getParent)() Returns the name of the parent type. | | Details ------- ### buildForm([FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") $builder, array $options) Builds the form. This method is called for each type in the hierarchy starting from the top most type. Type extensions can further modify the form. #### Parameters | | | | | --- | --- | --- | | [FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") | $builder | The form builder | | array | $options | The options | ### buildView([FormView](formview "Symfony\Component\Form\FormView") $view, [FormInterface](forminterface "Symfony\Component\Form\FormInterface") $form, array $options) Builds the form view. This method is called for each type in the hierarchy starting from the top most type. Type extensions can further modify the view. A view of a form is built before the views of the child forms are built. This means that you cannot access child views in this method. If you need to do so, move your logic to {@link finishView()} instead. #### Parameters | | | | | --- | --- | --- | | [FormView](formview "Symfony\Component\Form\FormView") | $view | The view | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | $form | The form | | array | $options | The options | ### finishView([FormView](formview "Symfony\Component\Form\FormView") $view, [FormInterface](forminterface "Symfony\Component\Form\FormInterface") $form, array $options) Finishes the form view. This method gets called for each type in the hierarchy starting from the top most type. Type extensions can further modify the view. When this method is called, views of the form's children have already been built and finished and can be accessed. You should only implement such logic in this method that actually accesses child views. For everything else you are recommended to implement {@link buildView()} instead. #### Parameters | | | | | --- | --- | --- | | [FormView](formview "Symfony\Component\Form\FormView") | $view | The view | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | $form | The form | | array | $options | The options | ### configureOptions([OptionsResolver](../optionsresolver/optionsresolver "Symfony\Component\OptionsResolver\OptionsResolver") $resolver) Configures the options for this type. #### Parameters | | | | | --- | --- | --- | | [OptionsResolver](../optionsresolver/optionsresolver "Symfony\Component\OptionsResolver\OptionsResolver") | $resolver | The resolver for the options | ### string getBlockPrefix() Returns the prefix of the template block name for this type. The block prefix defaults to the underscored short class name with the "Type" suffix removed (e.g. "UserProfileType" => "user\_profile"). #### Return Value | | | | --- | --- | | string | The prefix of the template block name | ### string|null getParent() Returns the name of the parent type. #### Return Value | | | | --- | --- | | string|null | The name of the parent type if any, null otherwise | symfony FormEvent FormEvent ========== class **FormEvent** extends [Event](../eventdispatcher/event "Symfony\Component\EventDispatcher\Event") Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $data | | | Methods ------- | | | | | --- | --- | --- | | bool | [isPropagationStopped](#method_isPropagationStopped)() Returns whether further event listeners should be triggered. | from [Event](../eventdispatcher/event#method_isPropagationStopped "Symfony\Component\EventDispatcher\Event") | | | [stopPropagation](#method_stopPropagation)() Stops the propagation of the event to further event listeners. | from [Event](../eventdispatcher/event#method_stopPropagation "Symfony\Component\EventDispatcher\Event") | | | [\_\_construct](#method___construct)([FormInterface](forminterface "Symfony\Component\Form\FormInterface") $form, $data) | | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | [getForm](#method_getForm)() Returns the form at the source of the event. | | | mixed | [getData](#method_getData)() Returns the data associated with this event. | | | | [setData](#method_setData)(mixed $data) Allows updating with some filtered data. | | Details ------- ### bool isPropagationStopped() Returns whether further event listeners should be triggered. #### Return Value | | | | --- | --- | | bool | Whether propagation was already stopped for this event | #### See also | | | | --- | --- | | [Event::stopPropagation](../eventdispatcher/event#method_stopPropagation "Symfony\Component\EventDispatcher\Event") | | ### stopPropagation() Stops the propagation of the event to further event listeners. If multiple event listeners are connected to the same event, no further event listener will be triggered once any trigger calls stopPropagation(). ### \_\_construct([FormInterface](forminterface "Symfony\Component\Form\FormInterface") $form, $data) #### Parameters | | | | | --- | --- | --- | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | $form | | | | $data | | ### [FormInterface](forminterface "Symfony\Component\Form\FormInterface") getForm() Returns the form at the source of the event. #### Return Value | | | | --- | --- | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | | ### mixed getData() Returns the data associated with this event. #### Return Value | | | | --- | --- | | mixed | | ### setData(mixed $data) Allows updating with some filtered data. #### Parameters | | | | | --- | --- | --- | | mixed | $data | | symfony ReversedTransformer ReversedTransformer ==================== class **ReversedTransformer** implements [DataTransformerInterface](datatransformerinterface "Symfony\Component\Form\DataTransformerInterface") Reverses a transformer. When the transform() method is called, the reversed transformer's reverseTransform() method is called and vice versa. Properties ---------- | | | | | | --- | --- | --- | --- | | protected | $reversedTransformer | | | Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([DataTransformerInterface](datatransformerinterface "Symfony\Component\Form\DataTransformerInterface") $reversedTransformer) | | | mixed | [transform](#method_transform)(mixed $value) Transforms a value from the original representation to a transformed representation. | | | mixed | [reverseTransform](#method_reverseTransform)(mixed $value) Transforms a value from the transformed representation to its original representation. | | Details ------- ### \_\_construct([DataTransformerInterface](datatransformerinterface "Symfony\Component\Form\DataTransformerInterface") $reversedTransformer) #### Parameters | | | | | --- | --- | --- | | [DataTransformerInterface](datatransformerinterface "Symfony\Component\Form\DataTransformerInterface") | $reversedTransformer | | ### mixed transform(mixed $value) Transforms a value from the original representation to a transformed representation. This method is called on two occasions inside a form field: 1. When the form field is initialized with the data attached from the datasource (object or array). 2. When data from a request is submitted using {@link Form::submit()} to transform the new input data back into the renderable format. For example if you have a date field and submit '2009-10-10' you might accept this value because its easily parsed, but the transformer still writes back "2009/10/10" onto the form field (for further displaying or other purposes). This method must be able to deal with empty values. Usually this will be NULL, but depending on your implementation other empty values are possible as well (such as empty strings). The reasoning behind this is that value transformers must be chainable. If the transform() method of the first value transformer outputs NULL, the second value transformer must be able to process that value. By convention, transform() should return an empty string if NULL is passed. #### Parameters | | | | | --- | --- | --- | | mixed | $value | The value in the original representation | #### Return Value | | | | --- | --- | | mixed | The value in the transformed representation | #### Exceptions | | | | --- | --- | | [TransformationFailedException](exception/transformationfailedexception "Symfony\Component\Form\Exception\TransformationFailedException") | when the transformation fails | ### mixed reverseTransform(mixed $value) Transforms a value from the transformed representation to its original representation. This method is called when {@link Form::submit()} is called to transform the requests tainted data into an acceptable format for your data processing/model layer. This method must be able to deal with empty values. Usually this will be an empty string, but depending on your implementation other empty values are possible as well (such as NULL). The reasoning behind this is that value transformers must be chainable. If the reverseTransform() method of the first value transformer outputs an empty string, the second value transformer must be able to process that value. By convention, reverseTransform() should return NULL if an empty string is passed. #### Parameters | | | | | --- | --- | --- | | mixed | $value | The value in the transformed representation | #### Return Value | | | | --- | --- | | mixed | The value in the original representation | #### Exceptions | | | | --- | --- | | [TransformationFailedException](exception/transformationfailedexception "Symfony\Component\Form\Exception\TransformationFailedException") | when the transformation fails | symfony FormBuilderInterface FormBuilderInterface ===================== interface **FormBuilderInterface** implements [Traversable](http://php.net/Traversable), [Countable](http://php.net/Countable), [FormConfigBuilderInterface](formconfigbuilderinterface "Symfony\Component\Form\FormConfigBuilderInterface") Methods ------- | | | | | --- | --- | --- | | [EventDispatcherInterface](../eventdispatcher/eventdispatcherinterface "Symfony\Component\EventDispatcher\EventDispatcherInterface") | [getEventDispatcher](#method_getEventDispatcher)() Returns the event dispatcher used to dispatch form events. | from [FormConfigInterface](formconfiginterface#method_getEventDispatcher "Symfony\Component\Form\FormConfigInterface") | | string | [getName](#method_getName)() Returns the name of the form used as HTTP parameter. | from [FormConfigInterface](formconfiginterface#method_getName "Symfony\Component\Form\FormConfigInterface") | | [PropertyPathInterface](../propertyaccess/propertypathinterface "Symfony\Component\PropertyAccess\PropertyPathInterface")|null | [getPropertyPath](#method_getPropertyPath)() Returns the property path that the form should be mapped to. | from [FormConfigInterface](formconfiginterface#method_getPropertyPath "Symfony\Component\Form\FormConfigInterface") | | bool | [getMapped](#method_getMapped)() Returns whether the form should be mapped to an element of its parent's data. | from [FormConfigInterface](formconfiginterface#method_getMapped "Symfony\Component\Form\FormConfigInterface") | | bool | [getByReference](#method_getByReference)() Returns whether the form's data should be modified by reference. | from [FormConfigInterface](formconfiginterface#method_getByReference "Symfony\Component\Form\FormConfigInterface") | | bool | [getInheritData](#method_getInheritData)() Returns whether the form should read and write the data of its parent. | from [FormConfigInterface](formconfiginterface#method_getInheritData "Symfony\Component\Form\FormConfigInterface") | | bool | [getCompound](#method_getCompound)() Returns whether the form is compound. | from [FormConfigInterface](formconfiginterface#method_getCompound "Symfony\Component\Form\FormConfigInterface") | | [ResolvedFormTypeInterface](resolvedformtypeinterface "Symfony\Component\Form\ResolvedFormTypeInterface") | [getType](#method_getType)() Returns the form types used to construct the form. | from [FormConfigInterface](formconfiginterface#method_getType "Symfony\Component\Form\FormConfigInterface") | | [DataTransformerInterface](datatransformerinterface "Symfony\Component\Form\DataTransformerInterface")[] | [getViewTransformers](#method_getViewTransformers)() Returns the view transformers of the form. | from [FormConfigInterface](formconfiginterface#method_getViewTransformers "Symfony\Component\Form\FormConfigInterface") | | [DataTransformerInterface](datatransformerinterface "Symfony\Component\Form\DataTransformerInterface")[] | [getModelTransformers](#method_getModelTransformers)() Returns the model transformers of the form. | from [FormConfigInterface](formconfiginterface#method_getModelTransformers "Symfony\Component\Form\FormConfigInterface") | | [DataMapperInterface](datamapperinterface "Symfony\Component\Form\DataMapperInterface")|null | [getDataMapper](#method_getDataMapper)() Returns the data mapper of the form. | from [FormConfigInterface](formconfiginterface#method_getDataMapper "Symfony\Component\Form\FormConfigInterface") | | bool | [getRequired](#method_getRequired)() Returns whether the form is required. | from [FormConfigInterface](formconfiginterface#method_getRequired "Symfony\Component\Form\FormConfigInterface") | | bool | [getDisabled](#method_getDisabled)() Returns whether the form is disabled. | from [FormConfigInterface](formconfiginterface#method_getDisabled "Symfony\Component\Form\FormConfigInterface") | | bool | [getErrorBubbling](#method_getErrorBubbling)() Returns whether errors attached to the form will bubble to its parent. | from [FormConfigInterface](formconfiginterface#method_getErrorBubbling "Symfony\Component\Form\FormConfigInterface") | | mixed | [getEmptyData](#method_getEmptyData)() Returns the data that should be returned when the form is empty. | from [FormConfigInterface](formconfiginterface#method_getEmptyData "Symfony\Component\Form\FormConfigInterface") | | array | [getAttributes](#method_getAttributes)() Returns additional attributes of the form. | from [FormConfigInterface](formconfiginterface#method_getAttributes "Symfony\Component\Form\FormConfigInterface") | | bool | [hasAttribute](#method_hasAttribute)(string $name) Returns whether the attribute with the given name exists. | from [FormConfigInterface](formconfiginterface#method_hasAttribute "Symfony\Component\Form\FormConfigInterface") | | mixed | [getAttribute](#method_getAttribute)(string $name, mixed $default = null) Returns the value of the given attribute. | from [FormConfigInterface](formconfiginterface#method_getAttribute "Symfony\Component\Form\FormConfigInterface") | | mixed | [getData](#method_getData)() Returns the initial data of the form. | from [FormConfigInterface](formconfiginterface#method_getData "Symfony\Component\Form\FormConfigInterface") | | string|null | [getDataClass](#method_getDataClass)() Returns the class of the form data or null if the data is scalar or an array. | from [FormConfigInterface](formconfiginterface#method_getDataClass "Symfony\Component\Form\FormConfigInterface") | | bool | [getDataLocked](#method_getDataLocked)() Returns whether the form's data is locked. | from [FormConfigInterface](formconfiginterface#method_getDataLocked "Symfony\Component\Form\FormConfigInterface") | | [FormFactoryInterface](formfactoryinterface "Symfony\Component\Form\FormFactoryInterface") | [getFormFactory](#method_getFormFactory)() Returns the form factory used for creating new forms. | from [FormConfigInterface](formconfiginterface#method_getFormFactory "Symfony\Component\Form\FormConfigInterface") | | string | [getAction](#method_getAction)() Returns the target URL of the form. | from [FormConfigInterface](formconfiginterface#method_getAction "Symfony\Component\Form\FormConfigInterface") | | string | [getMethod](#method_getMethod)() Returns the HTTP method used by the form. | from [FormConfigInterface](formconfiginterface#method_getMethod "Symfony\Component\Form\FormConfigInterface") | | [RequestHandlerInterface](requesthandlerinterface "Symfony\Component\Form\RequestHandlerInterface") | [getRequestHandler](#method_getRequestHandler)() Returns the request handler used by the form. | from [FormConfigInterface](formconfiginterface#method_getRequestHandler "Symfony\Component\Form\FormConfigInterface") | | bool | [getAutoInitialize](#method_getAutoInitialize)() Returns whether the form should be initialized upon creation. | from [FormConfigInterface](formconfiginterface#method_getAutoInitialize "Symfony\Component\Form\FormConfigInterface") | | array | [getOptions](#method_getOptions)() Returns all options passed during the construction of the form. | from [FormConfigInterface](formconfiginterface#method_getOptions "Symfony\Component\Form\FormConfigInterface") | | bool | [hasOption](#method_hasOption)(string $name) Returns whether a specific option exists. | from [FormConfigInterface](formconfiginterface#method_hasOption "Symfony\Component\Form\FormConfigInterface") | | mixed | [getOption](#method_getOption)(string $name, mixed $default = null) Returns the value of a specific option. | from [FormConfigInterface](formconfiginterface#method_getOption "Symfony\Component\Form\FormConfigInterface") | | $this | [addEventListener](#method_addEventListener)(string $eventName, callable $listener, int $priority = 0) Adds an event listener to an event on this form. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_addEventListener "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [addEventSubscriber](#method_addEventSubscriber)([EventSubscriberInterface](../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") $subscriber) Adds an event subscriber for events on this form. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_addEventSubscriber "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [addViewTransformer](#method_addViewTransformer)([DataTransformerInterface](datatransformerinterface "Symfony\Component\Form\DataTransformerInterface") $viewTransformer, bool $forcePrepend = false) Appends / prepends a transformer to the view transformer chain. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_addViewTransformer "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [resetViewTransformers](#method_resetViewTransformers)() Clears the view transformers. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_resetViewTransformers "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [addModelTransformer](#method_addModelTransformer)([DataTransformerInterface](datatransformerinterface "Symfony\Component\Form\DataTransformerInterface") $modelTransformer, bool $forceAppend = false) Prepends / appends a transformer to the normalization transformer chain. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_addModelTransformer "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [resetModelTransformers](#method_resetModelTransformers)() Clears the normalization transformers. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_resetModelTransformers "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [setAttribute](#method_setAttribute)(string $name, mixed $value) Sets the value for an attribute. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_setAttribute "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [setAttributes](#method_setAttributes)(array $attributes) Sets the attributes. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_setAttributes "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [setDataMapper](#method_setDataMapper)([DataMapperInterface](datamapperinterface "Symfony\Component\Form\DataMapperInterface") $dataMapper = null) Sets the data mapper used by the form. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_setDataMapper "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [setDisabled](#method_setDisabled)(bool $disabled) Set whether the form is disabled. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_setDisabled "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [setEmptyData](#method_setEmptyData)(mixed $emptyData) Sets the data used for the client data when no value is submitted. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_setEmptyData "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [setErrorBubbling](#method_setErrorBubbling)(bool $errorBubbling) Sets whether errors bubble up to the parent. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_setErrorBubbling "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [setRequired](#method_setRequired)(bool $required) Sets whether this field is required to be filled out when submitted. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_setRequired "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [setPropertyPath](#method_setPropertyPath)(string|[PropertyPathInterface](../propertyaccess/propertypathinterface "Symfony\Component\PropertyAccess\PropertyPathInterface")|null $propertyPath) Sets the property path that the form should be mapped to. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_setPropertyPath "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [setMapped](#method_setMapped)(bool $mapped) Sets whether the form should be mapped to an element of its parent's data. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_setMapped "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [setByReference](#method_setByReference)(bool $byReference) Sets whether the form's data should be modified by reference. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_setByReference "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [setInheritData](#method_setInheritData)(bool $inheritData) Sets whether the form should read and write the data of its parent. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_setInheritData "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [setCompound](#method_setCompound)(bool $compound) Sets whether the form should be compound. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_setCompound "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [setType](#method_setType)([ResolvedFormTypeInterface](resolvedformtypeinterface "Symfony\Component\Form\ResolvedFormTypeInterface") $type) Set the types. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_setType "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [setData](#method_setData)(mixed $data) Sets the initial data of the form. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_setData "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [setDataLocked](#method_setDataLocked)(bool $locked) Locks the form's data to the data passed in the configuration. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_setDataLocked "Symfony\Component\Form\FormConfigBuilderInterface") | | | [setFormFactory](#method_setFormFactory)([FormFactoryInterface](formfactoryinterface "Symfony\Component\Form\FormFactoryInterface") $formFactory) Sets the form factory used for creating new forms. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_setFormFactory "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [setAction](#method_setAction)(string $action) Sets the target URL of the form. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_setAction "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [setMethod](#method_setMethod)(string $method) Sets the HTTP method used by the form. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_setMethod "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [setRequestHandler](#method_setRequestHandler)([RequestHandlerInterface](requesthandlerinterface "Symfony\Component\Form\RequestHandlerInterface") $requestHandler) Sets the request handler used by the form. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_setRequestHandler "Symfony\Component\Form\FormConfigBuilderInterface") | | $this | [setAutoInitialize](#method_setAutoInitialize)(bool $initialize) Sets whether the form should be initialized automatically. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_setAutoInitialize "Symfony\Component\Form\FormConfigBuilderInterface") | | [FormConfigInterface](formconfiginterface "Symfony\Component\Form\FormConfigInterface") | [getFormConfig](#method_getFormConfig)() Builds and returns the form configuration. | from [FormConfigBuilderInterface](formconfigbuilderinterface#method_getFormConfig "Symfony\Component\Form\FormConfigBuilderInterface") | | [FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") | [add](#method_add)(string|int|[FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") $child, string|null $type = null, array $options = array()) Adds a new field to this group. A field must have a unique name within the group. Otherwise the existing field is overwritten. | | | [FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") | [create](#method_create)(string $name, string|null $type = null, array $options = array()) Creates a form builder. | | | [FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") | [get](#method_get)(string $name) Returns a child by name. | | | [FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") | [remove](#method_remove)(string $name) Removes the field with the given name. | | | bool | [has](#method_has)(string $name) Returns whether a field with the given name exists. | | | array | [all](#method_all)() Returns the children. | | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | [getForm](#method_getForm)() Creates the form. | | Details ------- ### [EventDispatcherInterface](../eventdispatcher/eventdispatcherinterface "Symfony\Component\EventDispatcher\EventDispatcherInterface") getEventDispatcher() Returns the event dispatcher used to dispatch form events. #### Return Value | | | | --- | --- | | [EventDispatcherInterface](../eventdispatcher/eventdispatcherinterface "Symfony\Component\EventDispatcher\EventDispatcherInterface") | The dispatcher | ### string getName() Returns the name of the form used as HTTP parameter. #### Return Value | | | | --- | --- | | string | The form name | ### [PropertyPathInterface](../propertyaccess/propertypathinterface "Symfony\Component\PropertyAccess\PropertyPathInterface")|null getPropertyPath() Returns the property path that the form should be mapped to. #### Return Value | | | | --- | --- | | [PropertyPathInterface](../propertyaccess/propertypathinterface "Symfony\Component\PropertyAccess\PropertyPathInterface")|null | The property path | ### bool getMapped() Returns whether the form should be mapped to an element of its parent's data. #### Return Value | | | | --- | --- | | bool | Whether the form is mapped | ### bool getByReference() Returns whether the form's data should be modified by reference. #### Return Value | | | | --- | --- | | bool | Whether to modify the form's data by reference | ### bool getInheritData() Returns whether the form should read and write the data of its parent. #### Return Value | | | | --- | --- | | bool | Whether the form should inherit its parent's data | ### bool getCompound() Returns whether the form is compound. This property is independent of whether the form actually has children. A form can be compound and have no children at all, like for example an empty collection form. #### Return Value | | | | --- | --- | | bool | Whether the form is compound | ### [ResolvedFormTypeInterface](resolvedformtypeinterface "Symfony\Component\Form\ResolvedFormTypeInterface") getType() Returns the form types used to construct the form. #### Return Value | | | | --- | --- | | [ResolvedFormTypeInterface](resolvedformtypeinterface "Symfony\Component\Form\ResolvedFormTypeInterface") | The form's type | ### [DataTransformerInterface](datatransformerinterface "Symfony\Component\Form\DataTransformerInterface")[] getViewTransformers() Returns the view transformers of the form. #### Return Value | | | | --- | --- | | [DataTransformerInterface](datatransformerinterface "Symfony\Component\Form\DataTransformerInterface")[] | An array of {@link DataTransformerInterface} instances | ### [DataTransformerInterface](datatransformerinterface "Symfony\Component\Form\DataTransformerInterface")[] getModelTransformers() Returns the model transformers of the form. #### Return Value | | | | --- | --- | | [DataTransformerInterface](datatransformerinterface "Symfony\Component\Form\DataTransformerInterface")[] | An array of {@link DataTransformerInterface} instances | ### [DataMapperInterface](datamapperinterface "Symfony\Component\Form\DataMapperInterface")|null getDataMapper() Returns the data mapper of the form. #### Return Value | | | | --- | --- | | [DataMapperInterface](datamapperinterface "Symfony\Component\Form\DataMapperInterface")|null | The data mapper | ### bool getRequired() Returns whether the form is required. #### Return Value | | | | --- | --- | | bool | Whether the form is required | ### bool getDisabled() Returns whether the form is disabled. #### Return Value | | | | --- | --- | | bool | Whether the form is disabled | ### bool getErrorBubbling() Returns whether errors attached to the form will bubble to its parent. #### Return Value | | | | --- | --- | | bool | Whether errors will bubble up | ### mixed getEmptyData() Returns the data that should be returned when the form is empty. #### Return Value | | | | --- | --- | | mixed | The data returned if the form is empty | ### array getAttributes() Returns additional attributes of the form. #### Return Value | | | | --- | --- | | array | An array of key-value combinations | ### bool hasAttribute(string $name) Returns whether the attribute with the given name exists. #### Parameters | | | | | --- | --- | --- | | string | $name | The attribute name | #### Return Value | | | | --- | --- | | bool | Whether the attribute exists | ### mixed getAttribute(string $name, mixed $default = null) Returns the value of the given attribute. #### Parameters | | | | | --- | --- | --- | | string | $name | The attribute name | | mixed | $default | The value returned if the attribute does not exist | #### Return Value | | | | --- | --- | | mixed | The attribute value | ### mixed getData() Returns the initial data of the form. #### Return Value | | | | --- | --- | | mixed | The initial form data | ### string|null getDataClass() Returns the class of the form data or null if the data is scalar or an array. #### Return Value | | | | --- | --- | | string|null | The data class or null | ### bool getDataLocked() Returns whether the form's data is locked. A form with locked data is restricted to the data passed in this configuration. The data can only be modified then by submitting the form. #### Return Value | | | | --- | --- | | bool | Whether the data is locked | ### [FormFactoryInterface](formfactoryinterface "Symfony\Component\Form\FormFactoryInterface") getFormFactory() Returns the form factory used for creating new forms. #### Return Value | | | | --- | --- | | [FormFactoryInterface](formfactoryinterface "Symfony\Component\Form\FormFactoryInterface") | The form factory | ### string getAction() Returns the target URL of the form. #### Return Value | | | | --- | --- | | string | The target URL of the form | ### string getMethod() Returns the HTTP method used by the form. #### Return Value | | | | --- | --- | | string | The HTTP method of the form | ### [RequestHandlerInterface](requesthandlerinterface "Symfony\Component\Form\RequestHandlerInterface") getRequestHandler() Returns the request handler used by the form. #### Return Value | | | | --- | --- | | [RequestHandlerInterface](requesthandlerinterface "Symfony\Component\Form\RequestHandlerInterface") | The request handler | ### bool getAutoInitialize() Returns whether the form should be initialized upon creation. #### Return Value | | | | --- | --- | | bool | returns true if the form should be initialized when created, false otherwise | ### array getOptions() Returns all options passed during the construction of the form. #### Return Value | | | | --- | --- | | array | The passed options | ### bool hasOption(string $name) Returns whether a specific option exists. #### Parameters | | | | | --- | --- | --- | | string | $name | The option name, | #### Return Value | | | | --- | --- | | bool | Whether the option exists | ### mixed getOption(string $name, mixed $default = null) Returns the value of a specific option. #### Parameters | | | | | --- | --- | --- | | string | $name | The option name | | mixed | $default | The value returned if the option does not exist | #### Return Value | | | | --- | --- | | mixed | The option value | ### $this addEventListener(string $eventName, callable $listener, int $priority = 0) Adds an event listener to an event on this form. #### Parameters | | | | | --- | --- | --- | | string | $eventName | The name of the event to listen to | | callable | $listener | The listener to execute | | int | $priority | The priority of the listener. Listeners with a higher priority are called before listeners with a lower priority. | #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this addEventSubscriber([EventSubscriberInterface](../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") $subscriber) Adds an event subscriber for events on this form. #### Parameters | | | | | --- | --- | --- | | [EventSubscriberInterface](../eventdispatcher/eventsubscriberinterface "Symfony\Component\EventDispatcher\EventSubscriberInterface") | $subscriber | | #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this addViewTransformer([DataTransformerInterface](datatransformerinterface "Symfony\Component\Form\DataTransformerInterface") $viewTransformer, bool $forcePrepend = false) Appends / prepends a transformer to the view transformer chain. The transform method of the transformer is used to convert data from the normalized to the view format. The reverseTransform method of the transformer is used to convert from the view to the normalized format. #### Parameters | | | | | --- | --- | --- | | [DataTransformerInterface](datatransformerinterface "Symfony\Component\Form\DataTransformerInterface") | $viewTransformer | | | bool | $forcePrepend | If set to true, prepend instead of appending | #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this resetViewTransformers() Clears the view transformers. #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this addModelTransformer([DataTransformerInterface](datatransformerinterface "Symfony\Component\Form\DataTransformerInterface") $modelTransformer, bool $forceAppend = false) Prepends / appends a transformer to the normalization transformer chain. The transform method of the transformer is used to convert data from the model to the normalized format. The reverseTransform method of the transformer is used to convert from the normalized to the model format. #### Parameters | | | | | --- | --- | --- | | [DataTransformerInterface](datatransformerinterface "Symfony\Component\Form\DataTransformerInterface") | $modelTransformer | | | bool | $forceAppend | If set to true, append instead of prepending | #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this resetModelTransformers() Clears the normalization transformers. #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this setAttribute(string $name, mixed $value) Sets the value for an attribute. #### Parameters | | | | | --- | --- | --- | | string | $name | The name of the attribute | | mixed | $value | The value of the attribute | #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this setAttributes(array $attributes) Sets the attributes. #### Parameters | | | | | --- | --- | --- | | array | $attributes | | #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this setDataMapper([DataMapperInterface](datamapperinterface "Symfony\Component\Form\DataMapperInterface") $dataMapper = null) Sets the data mapper used by the form. #### Parameters | | | | | --- | --- | --- | | [DataMapperInterface](datamapperinterface "Symfony\Component\Form\DataMapperInterface") | $dataMapper | | #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this setDisabled(bool $disabled) Set whether the form is disabled. #### Parameters | | | | | --- | --- | --- | | bool | $disabled | Whether the form is disabled | #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this setEmptyData(mixed $emptyData) Sets the data used for the client data when no value is submitted. #### Parameters | | | | | --- | --- | --- | | mixed | $emptyData | The empty data | #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this setErrorBubbling(bool $errorBubbling) Sets whether errors bubble up to the parent. #### Parameters | | | | | --- | --- | --- | | bool | $errorBubbling | | #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this setRequired(bool $required) Sets whether this field is required to be filled out when submitted. #### Parameters | | | | | --- | --- | --- | | bool | $required | | #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this setPropertyPath(string|[PropertyPathInterface](../propertyaccess/propertypathinterface "Symfony\Component\PropertyAccess\PropertyPathInterface")|null $propertyPath) Sets the property path that the form should be mapped to. #### Parameters | | | | | --- | --- | --- | | string|[PropertyPathInterface](../propertyaccess/propertypathinterface "Symfony\Component\PropertyAccess\PropertyPathInterface")|null | $propertyPath | The property path or null if the path should be set automatically based on the form's name | #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this setMapped(bool $mapped) Sets whether the form should be mapped to an element of its parent's data. #### Parameters | | | | | --- | --- | --- | | bool | $mapped | Whether the form should be mapped | #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this setByReference(bool $byReference) Sets whether the form's data should be modified by reference. #### Parameters | | | | | --- | --- | --- | | bool | $byReference | Whether the data should be modified by reference | #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this setInheritData(bool $inheritData) Sets whether the form should read and write the data of its parent. #### Parameters | | | | | --- | --- | --- | | bool | $inheritData | Whether the form should inherit its parent's data | #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this setCompound(bool $compound) Sets whether the form should be compound. #### Parameters | | | | | --- | --- | --- | | bool | $compound | Whether the form should be compound | #### Return Value | | | | --- | --- | | $this | The configuration object | #### See also | | | | --- | --- | | [FormConfigInterface::getCompound](formconfiginterface#method_getCompound "Symfony\Component\Form\FormConfigInterface") | | ### $this setType([ResolvedFormTypeInterface](resolvedformtypeinterface "Symfony\Component\Form\ResolvedFormTypeInterface") $type) Set the types. #### Parameters | | | | | --- | --- | --- | | [ResolvedFormTypeInterface](resolvedformtypeinterface "Symfony\Component\Form\ResolvedFormTypeInterface") | $type | | #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this setData(mixed $data) Sets the initial data of the form. #### Parameters | | | | | --- | --- | --- | | mixed | $data | The data of the form in application format | #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this setDataLocked(bool $locked) Locks the form's data to the data passed in the configuration. A form with locked data is restricted to the data passed in this configuration. The data can only be modified then by submitting the form. #### Parameters | | | | | --- | --- | --- | | bool | $locked | Whether to lock the default data | #### Return Value | | | | --- | --- | | $this | The configuration object | ### setFormFactory([FormFactoryInterface](formfactoryinterface "Symfony\Component\Form\FormFactoryInterface") $formFactory) Sets the form factory used for creating new forms. #### Parameters | | | | | --- | --- | --- | | [FormFactoryInterface](formfactoryinterface "Symfony\Component\Form\FormFactoryInterface") | $formFactory | | ### $this setAction(string $action) Sets the target URL of the form. #### Parameters | | | | | --- | --- | --- | | string | $action | The target URL of the form | #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this setMethod(string $method) Sets the HTTP method used by the form. #### Parameters | | | | | --- | --- | --- | | string | $method | The HTTP method of the form | #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this setRequestHandler([RequestHandlerInterface](requesthandlerinterface "Symfony\Component\Form\RequestHandlerInterface") $requestHandler) Sets the request handler used by the form. #### Parameters | | | | | --- | --- | --- | | [RequestHandlerInterface](requesthandlerinterface "Symfony\Component\Form\RequestHandlerInterface") | $requestHandler | | #### Return Value | | | | --- | --- | | $this | The configuration object | ### $this setAutoInitialize(bool $initialize) Sets whether the form should be initialized automatically. Should be set to true only for root forms. #### Parameters | | | | | --- | --- | --- | | bool | $initialize | true to initialize the form automatically, false to suppress automatic initialization. In the second case, you need to call {@link FormInterface::initialize()} manually | #### Return Value | | | | --- | --- | | $this | The configuration object | ### [FormConfigInterface](formconfiginterface "Symfony\Component\Form\FormConfigInterface") getFormConfig() Builds and returns the form configuration. #### Return Value | | | | --- | --- | | [FormConfigInterface](formconfiginterface "Symfony\Component\Form\FormConfigInterface") | | ### [FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") add(string|int|[FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") $child, string|null $type = null, array $options = array()) Adds a new field to this group. A field must have a unique name within the group. Otherwise the existing field is overwritten. If you add a nested group, this group should also be represented in the object hierarchy. #### Parameters | | | | | --- | --- | --- | | string|int|[FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") | $child | | | string|null | $type | | | array | $options | | #### Return Value | | | | --- | --- | | [FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") | | ### [FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") create(string $name, string|null $type = null, array $options = array()) Creates a form builder. #### Parameters | | | | | --- | --- | --- | | string | $name | The name of the form or the name of the property | | string|null | $type | The type of the form or null if name is a property | | array | $options | The options | #### Return Value | | | | --- | --- | | [FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") | | ### [FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") get(string $name) Returns a child by name. #### Parameters | | | | | --- | --- | --- | | string | $name | The name of the child | #### Return Value | | | | --- | --- | | [FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") | | #### Exceptions | | | | --- | --- | | [InvalidArgumentException](exception/invalidargumentexception "Symfony\Component\Form\Exception\InvalidArgumentException") | if the given child does not exist | ### [FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") remove(string $name) Removes the field with the given name. #### Parameters | | | | | --- | --- | --- | | string | $name | | #### Return Value | | | | --- | --- | | [FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") | | ### bool has(string $name) Returns whether a field with the given name exists. #### Parameters | | | | | --- | --- | --- | | string | $name | | #### Return Value | | | | --- | --- | | bool | | ### array all() Returns the children. #### Return Value | | | | --- | --- | | array | | ### [FormInterface](forminterface "Symfony\Component\Form\FormInterface") getForm() Creates the form. #### Return Value | | | | --- | --- | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | The form |
programming_docs
symfony ResolvedFormTypeInterface ResolvedFormTypeInterface ========================== interface **ResolvedFormTypeInterface** A wrapper for a form type and its extensions. Methods ------- | | | | | --- | --- | --- | | string | [getBlockPrefix](#method_getBlockPrefix)() Returns the prefix of the template block name for this type. | | | [ResolvedFormTypeInterface](resolvedformtypeinterface "Symfony\Component\Form\ResolvedFormTypeInterface")|null | [getParent](#method_getParent)() Returns the parent type. | | | [FormTypeInterface](formtypeinterface "Symfony\Component\Form\FormTypeInterface") | [getInnerType](#method_getInnerType)() Returns the wrapped form type. | | | [FormTypeExtensionInterface](formtypeextensioninterface "Symfony\Component\Form\FormTypeExtensionInterface")[] | [getTypeExtensions](#method_getTypeExtensions)() Returns the extensions of the wrapped form type. | | | [FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") | [createBuilder](#method_createBuilder)([FormFactoryInterface](formfactoryinterface "Symfony\Component\Form\FormFactoryInterface") $factory, string $name, array $options = array()) Creates a new form builder for this type. | | | [FormView](formview "Symfony\Component\Form\FormView") | [createView](#method_createView)([FormInterface](forminterface "Symfony\Component\Form\FormInterface") $form, [FormView](formview "Symfony\Component\Form\FormView") $parent = null) Creates a new form view for a form of this type. | | | | [buildForm](#method_buildForm)([FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") $builder, array $options) Configures a form builder for the type hierarchy. | | | | [buildView](#method_buildView)([FormView](formview "Symfony\Component\Form\FormView") $view, [FormInterface](forminterface "Symfony\Component\Form\FormInterface") $form, array $options) Configures a form view for the type hierarchy. | | | | [finishView](#method_finishView)([FormView](formview "Symfony\Component\Form\FormView") $view, [FormInterface](forminterface "Symfony\Component\Form\FormInterface") $form, array $options) Finishes a form view for the type hierarchy. | | | [OptionsResolver](../optionsresolver/optionsresolver "Symfony\Component\OptionsResolver\OptionsResolver") | [getOptionsResolver](#method_getOptionsResolver)() Returns the configured options resolver used for this type. | | Details ------- ### string getBlockPrefix() Returns the prefix of the template block name for this type. #### Return Value | | | | --- | --- | | string | The prefix of the template block name | ### [ResolvedFormTypeInterface](resolvedformtypeinterface "Symfony\Component\Form\ResolvedFormTypeInterface")|null getParent() Returns the parent type. #### Return Value | | | | --- | --- | | [ResolvedFormTypeInterface](resolvedformtypeinterface "Symfony\Component\Form\ResolvedFormTypeInterface")|null | The parent type or null | ### [FormTypeInterface](formtypeinterface "Symfony\Component\Form\FormTypeInterface") getInnerType() Returns the wrapped form type. #### Return Value | | | | --- | --- | | [FormTypeInterface](formtypeinterface "Symfony\Component\Form\FormTypeInterface") | The wrapped form type | ### [FormTypeExtensionInterface](formtypeextensioninterface "Symfony\Component\Form\FormTypeExtensionInterface")[] getTypeExtensions() Returns the extensions of the wrapped form type. #### Return Value | | | | --- | --- | | [FormTypeExtensionInterface](formtypeextensioninterface "Symfony\Component\Form\FormTypeExtensionInterface")[] | An array of {@link FormTypeExtensionInterface} instances | ### [FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") createBuilder([FormFactoryInterface](formfactoryinterface "Symfony\Component\Form\FormFactoryInterface") $factory, string $name, array $options = array()) Creates a new form builder for this type. #### Parameters | | | | | --- | --- | --- | | [FormFactoryInterface](formfactoryinterface "Symfony\Component\Form\FormFactoryInterface") | $factory | The form factory | | string | $name | The name for the builder | | array | $options | The builder options | #### Return Value | | | | --- | --- | | [FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") | The created form builder | ### [FormView](formview "Symfony\Component\Form\FormView") createView([FormInterface](forminterface "Symfony\Component\Form\FormInterface") $form, [FormView](formview "Symfony\Component\Form\FormView") $parent = null) Creates a new form view for a form of this type. #### Parameters | | | | | --- | --- | --- | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | $form | The form to create a view for | | [FormView](formview "Symfony\Component\Form\FormView") | $parent | The parent view or null | #### Return Value | | | | --- | --- | | [FormView](formview "Symfony\Component\Form\FormView") | The created form view | ### buildForm([FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") $builder, array $options) Configures a form builder for the type hierarchy. #### Parameters | | | | | --- | --- | --- | | [FormBuilderInterface](formbuilderinterface "Symfony\Component\Form\FormBuilderInterface") | $builder | The builder to configure | | array | $options | The options used for the configuration | ### buildView([FormView](formview "Symfony\Component\Form\FormView") $view, [FormInterface](forminterface "Symfony\Component\Form\FormInterface") $form, array $options) Configures a form view for the type hierarchy. It is called before the children of the view are built. #### Parameters | | | | | --- | --- | --- | | [FormView](formview "Symfony\Component\Form\FormView") | $view | The form view to configure | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | $form | The form corresponding to the view | | array | $options | The options used for the configuration | ### finishView([FormView](formview "Symfony\Component\Form\FormView") $view, [FormInterface](forminterface "Symfony\Component\Form\FormInterface") $form, array $options) Finishes a form view for the type hierarchy. It is called after the children of the view have been built. #### Parameters | | | | | --- | --- | --- | | [FormView](formview "Symfony\Component\Form\FormView") | $view | The form view to configure | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | $form | The form corresponding to the view | | array | $options | The options used for the configuration | ### [OptionsResolver](../optionsresolver/optionsresolver "Symfony\Component\OptionsResolver\OptionsResolver") getOptionsResolver() Returns the configured options resolver used for this type. #### Return Value | | | | --- | --- | | [OptionsResolver](../optionsresolver/optionsresolver "Symfony\Component\OptionsResolver\OptionsResolver") | The options resolver | symfony Symfony\Component\Form\Extension Symfony\Component\Form\Extension ================================ Namespaces ---------- [Symfony\Component\Form\Extension\Core](extension/core)[Symfony\Component\Form\Extension\Csrf](extension/csrf)[Symfony\Component\Form\Extension\DataCollector](extension/datacollector)[Symfony\Component\Form\Extension\DependencyInjection](extension/dependencyinjection)[Symfony\Component\Form\Extension\HttpFoundation](extension/httpfoundation)[Symfony\Component\Form\Extension\Templating](extension/templating)[Symfony\Component\Form\Extension\Validator](extension/validator) symfony Form Form ===== class **Form** implements [IteratorAggregate](http://php.net/IteratorAggregate), [FormInterface](forminterface "Symfony\Component\Form\FormInterface") Form represents a form. To implement your own form fields, you need to have a thorough understanding of the data flow within a form. A form stores its data in three different representations: (1) the "model" format required by the form's object (2) the "normalized" format for internal processing (3) the "view" format used for display A date field, for example, may store a date as "Y-m-d" string (1) in the object. To facilitate processing in the field, this value is normalized to a DateTime object (2). In the HTML representation of your form, a localized string (3) is presented to and modified by the user. In most cases, format (1) and format (2) will be the same. For example, a checkbox field uses a Boolean value for both internal processing and storage in the object. In these cases you simply need to set a value transformer to convert between formats (2) and (3). You can do this by calling addViewTransformer(). In some cases though it makes sense to make format (1) configurable. To demonstrate this, let's extend our above date field to store the value either as "Y-m-d" string or as timestamp. Internally we still want to use a DateTime object for processing. To convert the data from string/integer to DateTime you can set a normalization transformer by calling addModelTransformer(). The normalized data is then converted to the displayed data as described before. The conversions (1) -> (2) -> (3) use the transform methods of the transformers. The conversions (3) -> (2) -> (1) use the reverseTransform methods of the transformers. Methods ------- | | | | | --- | --- | --- | | | [\_\_construct](#method___construct)([FormConfigInterface](formconfiginterface "Symfony\Component\Form\FormConfigInterface") $config) Creates a new form based on the given configuration. | | | | [\_\_clone](#method___clone)() | | | [FormConfigInterface](formconfiginterface "Symfony\Component\Form\FormConfigInterface") | [getConfig](#method_getConfig)() Returns the form's configuration. | | | string | [getName](#method_getName)() Returns the name by which the form is identified in forms. | | | [PropertyPathInterface](../propertyaccess/propertypathinterface "Symfony\Component\PropertyAccess\PropertyPathInterface")|null | [getPropertyPath](#method_getPropertyPath)() Returns the property path that the form is mapped to. | | | bool | [isRequired](#method_isRequired)() Returns whether the form is required to be filled out. | | | bool | [isDisabled](#method_isDisabled)() Returns whether this form is disabled. | | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | [setParent](#method_setParent)([FormInterface](forminterface "Symfony\Component\Form\FormInterface") $parent = null) Sets the parent form. | | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface")|null | [getParent](#method_getParent)() Returns the parent form. | | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | [getRoot](#method_getRoot)() Returns the root of the form tree. | | | bool | [isRoot](#method_isRoot)() Returns whether the field is the root of the form tree. | | | $this | [setData](#method_setData)(mixed $modelData) Updates the form with default data. | | | mixed | [getData](#method_getData)() Returns the data in the format needed for the underlying object. | | | mixed | [getNormData](#method_getNormData)() Returns the normalized data of the field. | | | mixed | [getViewData](#method_getViewData)() Returns the data transformed by the value transformer. | | | array | [getExtraData](#method_getExtraData)() Returns the extra data. | | | $this | [initialize](#method_initialize)() Initializes the form tree. | | | $this | [handleRequest](#method_handleRequest)(mixed $request = null) Inspects the given request and calls {@link submit()} if the form was submitted. | | | $this | [submit](#method_submit)(mixed $submittedData, bool $clearMissing = true) Submits data to the form, transforms and validates it. | | | $this | [addError](#method_addError)([FormError](formerror "Symfony\Component\Form\FormError") $error) Adds an error to this form. | | | bool | [isSubmitted](#method_isSubmitted)() Returns whether the form is submitted. | | | bool | [isSynchronized](#method_isSynchronized)() Returns whether the data in the different formats is synchronized. | | | [TransformationFailedException](exception/transformationfailedexception "Symfony\Component\Form\Exception\TransformationFailedException")|null | [getTransformationFailure](#method_getTransformationFailure)() Returns the data transformation failure, if any. | | | bool | [isEmpty](#method_isEmpty)() Returns whether the form is empty. | | | bool | [isValid](#method_isValid)() Returns whether the form and all children are valid. | | | [Button](button "Symfony\Component\Form\Button")|null | [getClickedButton](#method_getClickedButton)() Returns the button that was used to submit the form. | | | [FormErrorIterator](formerroriterator "Symfony\Component\Form\FormErrorIterator") | [getErrors](#method_getErrors)(bool $deep = false, bool $flatten = true) Returns the errors of this form. | | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface")[] | [all](#method_all)() Returns all children in this group. | | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | [add](#method_add)([FormInterface](forminterface "Symfony\Component\Form\FormInterface")|string|int $child, string|null $type = null, array $options = array()) Adds or replaces a child to the form. | | | $this | [remove](#method_remove)(string $name) Removes a child from the form. | | | bool | [has](#method_has)(string $name) Returns whether a child with the given name exists. | | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | [get](#method_get)(string $name) Returns the child with the given name. | | | bool | [offsetExists](#method_offsetExists)(string $name) Returns whether a child with the given name exists (implements the \ArrayAccess interface). | | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | [offsetGet](#method_offsetGet)(string $name) Returns the child with the given name (implements the \ArrayAccess interface). | | | | [offsetSet](#method_offsetSet)(string $name, [FormInterface](forminterface "Symfony\Component\Form\FormInterface") $child) Adds a child to the form (implements the \ArrayAccess interface). | | | | [offsetUnset](#method_offsetUnset)(string $name) Removes the child with the given name from the form (implements the \ArrayAccess interface). | | | [Traversable](http://php.net/Traversable)|[FormInterface](forminterface "Symfony\Component\Form\FormInterface")[] | [getIterator](#method_getIterator)() Returns the iterator for this group. | | | int | [count](#method_count)() Returns the number of form children (implements the \Countable interface). | | | [FormView](formview "Symfony\Component\Form\FormView") | [createView](#method_createView)([FormView](formview "Symfony\Component\Form\FormView") $parent = null) Creates a view. | | Details ------- ### \_\_construct([FormConfigInterface](formconfiginterface "Symfony\Component\Form\FormConfigInterface") $config) Creates a new form based on the given configuration. #### Parameters | | | | | --- | --- | --- | | [FormConfigInterface](formconfiginterface "Symfony\Component\Form\FormConfigInterface") | $config | | #### Exceptions | | | | --- | --- | | [LogicException](exception/logicexception "Symfony\Component\Form\Exception\LogicException") | if a data mapper is not provided for a compound form | ### \_\_clone() ### [FormConfigInterface](formconfiginterface "Symfony\Component\Form\FormConfigInterface") getConfig() Returns the form's configuration. #### Return Value | | | | --- | --- | | [FormConfigInterface](formconfiginterface "Symfony\Component\Form\FormConfigInterface") | The configuration | ### string getName() Returns the name by which the form is identified in forms. #### Return Value | | | | --- | --- | | string | The name of the form | ### [PropertyPathInterface](../propertyaccess/propertypathinterface "Symfony\Component\PropertyAccess\PropertyPathInterface")|null getPropertyPath() Returns the property path that the form is mapped to. #### Return Value | | | | --- | --- | | [PropertyPathInterface](../propertyaccess/propertypathinterface "Symfony\Component\PropertyAccess\PropertyPathInterface")|null | The property path | ### bool isRequired() Returns whether the form is required to be filled out. If the form has a parent and the parent is not required, this method will always return false. Otherwise the value set with setRequired() is returned. #### Return Value | | | | --- | --- | | bool | | ### bool isDisabled() Returns whether this form is disabled. The content of a disabled form is displayed, but not allowed to be modified. The validation of modified disabled forms should fail. Forms whose parents are disabled are considered disabled regardless of their own state. #### Return Value | | | | --- | --- | | bool | | ### [FormInterface](forminterface "Symfony\Component\Form\FormInterface") setParent([FormInterface](forminterface "Symfony\Component\Form\FormInterface") $parent = null) Sets the parent form. #### Parameters | | | | | --- | --- | --- | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | $parent | | #### Return Value | | | | --- | --- | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | | #### Exceptions | | | | --- | --- | | [AlreadySubmittedException](exception/alreadysubmittedexception "Symfony\Component\Form\Exception\AlreadySubmittedException") | if the form has already been submitted | | [LogicException](exception/logicexception "Symfony\Component\Form\Exception\LogicException") | when trying to set a parent for a form with an empty name | ### [FormInterface](forminterface "Symfony\Component\Form\FormInterface")|null getParent() Returns the parent form. #### Return Value | | | | --- | --- | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface")|null | The parent form or null if there is none | ### [FormInterface](forminterface "Symfony\Component\Form\FormInterface") getRoot() Returns the root of the form tree. #### Return Value | | | | --- | --- | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | The root of the tree | ### bool isRoot() Returns whether the field is the root of the form tree. #### Return Value | | | | --- | --- | | bool | | ### $this setData(mixed $modelData) Updates the form with default data. #### Parameters | | | | | --- | --- | --- | | mixed | $modelData | The data formatted as expected for the underlying object | #### Return Value | | | | --- | --- | | $this | | #### Exceptions | | | | --- | --- | | [AlreadySubmittedException](exception/alreadysubmittedexception "Symfony\Component\Form\Exception\AlreadySubmittedException") | if the form has already been submitted | | [LogicException](exception/logicexception "Symfony\Component\Form\Exception\LogicException") | If listeners try to call setData in a cycle. Or if the view data does not match the expected type according to {@link FormConfigInterface::getDataClass}. | ### mixed getData() Returns the data in the format needed for the underlying object. #### Return Value | | | | --- | --- | | mixed | | ### mixed getNormData() Returns the normalized data of the field. #### Return Value | | | | --- | --- | | mixed | when the field is not submitted, the default data is returned. When the field is submitted, the normalized submitted data is returned if the field is valid, null otherwise | ### mixed getViewData() Returns the data transformed by the value transformer. #### Return Value | | | | --- | --- | | mixed | | ### array getExtraData() Returns the extra data. #### Return Value | | | | --- | --- | | array | The submitted data which do not belong to a child | ### $this initialize() Initializes the form tree. Should be called on the root form after constructing the tree. #### Return Value | | | | --- | --- | | $this | | ### $this handleRequest(mixed $request = null) Inspects the given request and calls {@link submit()} if the form was submitted. Internally, the request is forwarded to the configured {@link RequestHandlerInterface} instance, which determines whether to submit the form or not. #### Parameters | | | | | --- | --- | --- | | mixed | $request | The request to handle | #### Return Value | | | | --- | --- | | $this | | ### $this submit(mixed $submittedData, bool $clearMissing = true) Submits data to the form, transforms and validates it. #### Parameters | | | | | --- | --- | --- | | mixed | $submittedData | The submitted data | | bool | $clearMissing | Whether to set fields to NULL when they are missing in the submitted data | #### Return Value | | | | --- | --- | | $this | | #### Exceptions | | | | --- | --- | | [AlreadySubmittedException](exception/alreadysubmittedexception "Symfony\Component\Form\Exception\AlreadySubmittedException") | if the form has already been submitted | ### $this addError([FormError](formerror "Symfony\Component\Form\FormError") $error) Adds an error to this form. #### Parameters | | | | | --- | --- | --- | | [FormError](formerror "Symfony\Component\Form\FormError") | $error | | #### Return Value | | | | --- | --- | | $this | | ### bool isSubmitted() Returns whether the form is submitted. #### Return Value | | | | --- | --- | | bool | true if the form is submitted, false otherwise | ### bool isSynchronized() Returns whether the data in the different formats is synchronized. If the data is not synchronized, you can get the transformation failure by calling {@link getTransformationFailure()}. #### Return Value | | | | --- | --- | | bool | | ### [TransformationFailedException](exception/transformationfailedexception "Symfony\Component\Form\Exception\TransformationFailedException")|null getTransformationFailure() Returns the data transformation failure, if any. #### Return Value | | | | --- | --- | | [TransformationFailedException](exception/transformationfailedexception "Symfony\Component\Form\Exception\TransformationFailedException")|null | The transformation failure | ### bool isEmpty() Returns whether the form is empty. #### Return Value | | | | --- | --- | | bool | | ### bool isValid() Returns whether the form and all children are valid. #### Return Value | | | | --- | --- | | bool | | #### Exceptions | | | | --- | --- | | [LogicException](exception/logicexception "Symfony\Component\Form\Exception\LogicException") | if the form is not submitted | ### [Button](button "Symfony\Component\Form\Button")|null getClickedButton() Returns the button that was used to submit the form. #### Return Value | | | | --- | --- | | [Button](button "Symfony\Component\Form\Button")|null | The clicked button or NULL if the form was not submitted | ### [FormErrorIterator](formerroriterator "Symfony\Component\Form\FormErrorIterator") getErrors(bool $deep = false, bool $flatten = true) Returns the errors of this form. #### Parameters | | | | | --- | --- | --- | | bool | $deep | Whether to include errors of child forms as well | | bool | $flatten | Whether to flatten the list of errors in case $deep is set to true | #### Return Value | | | | --- | --- | | [FormErrorIterator](formerroriterator "Symfony\Component\Form\FormErrorIterator") | An iterator over the {@link FormError} instances that where added to this form | ### [FormInterface](forminterface "Symfony\Component\Form\FormInterface")[] all() Returns all children in this group. #### Return Value | | | | --- | --- | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface")[] | | ### [FormInterface](forminterface "Symfony\Component\Form\FormInterface") add([FormInterface](forminterface "Symfony\Component\Form\FormInterface")|string|int $child, string|null $type = null, array $options = array()) Adds or replaces a child to the form. #### Parameters | | | | | --- | --- | --- | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface")|string|int | $child | The FormInterface instance or the name of the child | | string|null | $type | The child's type, if a name was passed | | array | $options | The child's options, if a name was passed | #### Return Value | | | | --- | --- | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | | #### Exceptions | | | | --- | --- | | [AlreadySubmittedException](exception/alreadysubmittedexception "Symfony\Component\Form\Exception\AlreadySubmittedException") | if the form has already been submitted | | [LogicException](exception/logicexception "Symfony\Component\Form\Exception\LogicException") | when trying to add a child to a non-compound form | | [UnexpectedTypeException](exception/unexpectedtypeexception "Symfony\Component\Form\Exception\UnexpectedTypeException") | if $child or $type has an unexpected type | ### $this remove(string $name) Removes a child from the form. #### Parameters | | | | | --- | --- | --- | | string | $name | The name of the child to remove | #### Return Value | | | | --- | --- | | $this | | #### Exceptions | | | | --- | --- | | [AlreadySubmittedException](exception/alreadysubmittedexception "Symfony\Component\Form\Exception\AlreadySubmittedException") | if the form has already been submitted | ### bool has(string $name) Returns whether a child with the given name exists. #### Parameters | | | | | --- | --- | --- | | string | $name | The name of the child | #### Return Value | | | | --- | --- | | bool | | ### [FormInterface](forminterface "Symfony\Component\Form\FormInterface") get(string $name) Returns the child with the given name. #### Parameters | | | | | --- | --- | --- | | string | $name | The name of the child | #### Return Value | | | | --- | --- | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | | #### Exceptions | | | | --- | --- | | [OutOfBoundsException](http://php.net/OutOfBoundsException) | if the named child does not exist | ### bool offsetExists(string $name) Returns whether a child with the given name exists (implements the \ArrayAccess interface). #### Parameters | | | | | --- | --- | --- | | string | $name | The name of the child | #### Return Value | | | | --- | --- | | bool | | ### [FormInterface](forminterface "Symfony\Component\Form\FormInterface") offsetGet(string $name) Returns the child with the given name (implements the \ArrayAccess interface). #### Parameters | | | | | --- | --- | --- | | string | $name | The name of the child | #### Return Value | | | | --- | --- | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | The child form | #### Exceptions | | | | --- | --- | | [OutOfBoundsException](http://php.net/OutOfBoundsException) | if the named child does not exist | ### offsetSet(string $name, [FormInterface](forminterface "Symfony\Component\Form\FormInterface") $child) Adds a child to the form (implements the \ArrayAccess interface). #### Parameters | | | | | --- | --- | --- | | string | $name | Ignored. The name of the child is used | | [FormInterface](forminterface "Symfony\Component\Form\FormInterface") | $child | The child to be added | #### Exceptions | | | | --- | --- | | [AlreadySubmittedException](exception/alreadysubmittedexception "Symfony\Component\Form\Exception\AlreadySubmittedException") | if the form has already been submitted | | [LogicException](exception/logicexception "Symfony\Component\Form\Exception\LogicException") | when trying to add a child to a non-compound form | #### See also | | | | --- | --- | | [Form::add](form#method_add "Symfony\Component\Form\Form") | | ### offsetUnset(string $name) Removes the child with the given name from the form (implements the \ArrayAccess interface). #### Parameters | | | | | --- | --- | --- | | string | $name | The name of the child to remove | #### Exceptions | | | | --- | --- | | [AlreadySubmittedException](exception/alreadysubmittedexception "Symfony\Component\Form\Exception\AlreadySubmittedException") | if the form has already been submitted | ### [Traversable](http://php.net/Traversable)|[FormInterface](forminterface "Symfony\Component\Form\FormInterface")[] getIterator() Returns the iterator for this group. #### Return Value | | | | --- | --- | | [Traversable](http://php.net/Traversable)|[FormInterface](forminterface "Symfony\Component\Form\FormInterface")[] | | ### int count() Returns the number of form children (implements the \Countable interface). #### Return Value | | | | --- | --- | | int | The number of embedded form children | ### [FormView](formview "Symfony\Component\Form\FormView") createView([FormView](formview "Symfony\Component\Form\FormView") $parent = null) Creates a view. #### Parameters | | | | | --- | --- | --- | | [FormView](formview "Symfony\Component\Form\FormView") | $parent | | #### Return Value | | | | --- | --- | | [FormView](formview "Symfony\Component\Form\FormView") | The view |
programming_docs