|
1 |
| -### Coercion |
2 |
| - |
3 | 1 | Utility functions for coercing `@Input`s into specific types.
|
| 2 | + |
| 3 | +### Example |
| 4 | + |
| 5 | +```ts |
| 6 | +import {Directive, ElementRef, HostListener} from '@angular/core'; |
| 7 | +import { |
| 8 | + coerceBooleanProperty, |
| 9 | + BooleanInput, |
| 10 | + NumberInput, |
| 11 | + coerceNumberProperty, |
| 12 | + coerceElement, |
| 13 | +} from '@angular/cdk/coercion'; |
| 14 | + |
| 15 | +@Directive({ |
| 16 | + selector: 'my-button', |
| 17 | + host: { |
| 18 | + '[disabled]': 'disabled', |
| 19 | + '(click)': 'greet()', |
| 20 | + } |
| 21 | +}) |
| 22 | +class MyButton { |
| 23 | + // Using `coerceBooleanProperty` allows for the disabled value of a button to be set as |
| 24 | + // `<my-button disabled></my-button>` instead of `<my-button [disabled]="true"></my-button>`. |
| 25 | + // It also allows for a string to be passed like `<my-button disabled="true"></my-button>`. |
| 26 | + @Input() |
| 27 | + get disabled() { return this._disabled; } |
| 28 | + set disabled(value: any) { |
| 29 | + this._disabled = coerceBooleanProperty(value); |
| 30 | + } |
| 31 | + private _disabled = false; |
| 32 | + |
| 33 | + // `coerceNumberProperty` turns any value coming in from the view into a number, allowing the |
| 34 | + // consumer to use a shorthand string while storing the parsed number in memory. E.g. the consumer can write: |
| 35 | + // `<my-button greetDelay="500"></my-button>` instead of `<my-button [greetDelay]="500"></my-button>`. |
| 36 | + // The second parameter specifies a fallback value to be used if the value can't be |
| 37 | + // parsed to a number. |
| 38 | + @Input() |
| 39 | + get greetDelay() { return this._greetDelay; } |
| 40 | + set greetDelay(value: any) { |
| 41 | + this._greetDelay = coerceNumberProperty(value, 0); |
| 42 | + } |
| 43 | + private _greetDelay = 0; |
| 44 | + |
| 45 | + greet() { |
| 46 | + setTimeout(() => alert('Hello!'), this.greetDelay); |
| 47 | + } |
| 48 | + |
| 49 | + // `coerceElement` allows you to accept either an `ElementRef` |
| 50 | + // or a raw DOM node and to always return a DOM node. |
| 51 | + getElement(elementOrRef: ElementRef<HTMLElement> | HTMLElement): HTMLElement { |
| 52 | + return coerceElement(elementOrRef); |
| 53 | + } |
| 54 | + |
| 55 | + // Required so that the template type checker can infer the type of the coerced inputs. |
| 56 | + static ngAcceptInputType_disabled: BooleanInput; |
| 57 | + static ngAcceptInputType_greetDelay: NumberInput; |
| 58 | +} |
| 59 | +``` |
0 commit comments