Skip to content

Commit 0b04570

Browse files
authored
docs(cdk/coercion): expand overview (#22791)
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 8d95c2f commit 0b04570

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+
'(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

Comments
 (0)