Skip to content

Commit d318b67

Browse files
committed
docs(cdk/coercion): expand overview
Companion PR to angular/material.angular.io#994. Expands the overview of the coercion package so that we have more than one sentence to show.
1 parent 89c8474 commit d318b67

File tree

1 file changed

+58
-2
lines changed

1 file changed

+58
-2
lines changed

src/cdk/coercion/coercion.md

Lines changed: 58 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,59 @@
1-
### Coercion
2-
31
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+
}
20+
})
21+
class MyButton {
22+
// Using `coerceBooleanProperty` allows for the disabled value of a button to be set as
23+
// `<my-button disabled></my-button>` instead of `<my-button [disabled]="true"></my-button>`.
24+
// It also allows for a string to be passed like `<my-button disabled="true"></my-button>`.
25+
@Input()
26+
get disabled() { return this._disabled; }
27+
set disabled(value: any) {
28+
this._disabled = coerceBooleanProperty(value);
29+
}
30+
private _disabled = false;
31+
32+
// Using `coerceNumberProperty` allows for any value to be set to `greetDelay` while ensuring
33+
// that a number is always returned. E.g. the consumer can write:
34+
// `<my-button greetDelay="500"></my-button>` instead of `<my-button [greetDelay]="500"></my-button>`.
35+
// The second parameter specifies a fallback value to be used if the value can't be
36+
// parsed to a number.
37+
@Input()
38+
get greetDelay() { return this._greetDelay; }
39+
set greetDelay(value: any) {
40+
this._greetDelay = coerceNumberProperty(value, 0);
41+
}
42+
private _greetDelay = 0;
43+
44+
@HostListener('click')
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: BooleanInput;
58+
}
59+
```

0 commit comments

Comments
 (0)