|
| 1 | +--- |
| 2 | +title: Putting constraints on selectors |
| 3 | +description: "Making our components and directives more robust by putting constraints on their selectors" |
| 4 | +tags: ["angular"] |
| 5 | +pubDate: Mar 02, 2023 |
| 6 | +contributedBy: "@Nartc1410" |
| 7 | +--- |
| 8 | + |
| 9 | +`Component#selector` and `Directive#selector` are just like CSS Selector. This means we can utilize some CSS pseudo-class |
| 10 | +to put constraints on our `selector`, making them more robust and provide better DX to our consumers |
| 11 | + |
| 12 | +Suppose we have the following `NgxLilGui` component that wraps the `lil-gui` library. |
| 13 | + |
| 14 | +> To learn more about `lil-gui`, visit [https://lil-gui.georgealways.com/](https://lil-gui.georgealways.com/) |
| 15 | +
|
| 16 | +```ts |
| 17 | +@Component({ |
| 18 | + selector: "ngx-lil-gui", |
| 19 | + template: ` <ng-content></ng-content> `, |
| 20 | + standalone: true, |
| 21 | +}) |
| 22 | +export class NgxLilGui implements OnInit, OnDestroy { |
| 23 | + @Input() config: Config; |
| 24 | + @Input() object: Record<string, any>; |
| 25 | + |
| 26 | + /* ... */ |
| 27 | +} |
| 28 | +``` |
| 29 | + |
| 30 | +To make it flexible for the consumers, we allow the consumers to use `config` OR `object` to control the `lil-gui` library. |
| 31 | +In addition, the consumers can also use `<ngx-lil-gui>` without passing in anything. In this case, `<ngx-lil-gui>` acts as a |
| 32 | +group of other `<ngx-lil-gui>` |
| 33 | + |
| 34 | +```html |
| 35 | +<ng-container #anchor /> |
| 36 | +<span #spanElement>This is a span</span> |
| 37 | + |
| 38 | +<ngx-lil-gui> |
| 39 | + <!-- config object contains a dynamic HTMLElement that we can control --> |
| 40 | + <ngx-lil-gui [config]="config" /> |
| 41 | + <ngx-lil-gui title="SPAN" [object]="spanElement.style" /> |
| 42 | +</ngx-lil-gui> |
| 43 | +``` |
| 44 | + |
| 45 | +However, there's nothing to stop the consumers to use both `[config]` and `[object]` on `<ngx-lil-gui>` |
| 46 | + |
| 47 | +```html |
| 48 | +<ngx-lil-gui [config]="config" [object]="object" /> |
| 49 | +``` |
| 50 | + |
| 51 | +To apply this constraint, we can modify our selector as follow: |
| 52 | + |
| 53 | +```ts |
| 54 | +@Component({ |
| 55 | + selector: ` |
| 56 | + ngx-lil-gui:not([config]):not([object]), |
| 57 | + ngx-lil-gui[config]:not([object]), |
| 58 | + ngx-lil-gui[object]:not([config]) |
| 59 | + `, |
| 60 | + /* ... */ |
| 61 | +}) |
| 62 | +export class NgxLilGui implements OnInit, OnDestroy { |
| 63 | + /* ... */ |
| 64 | +} |
| 65 | +``` |
| 66 | + |
| 67 | +Now, the consumers can instantiate `NgxLilGui` component by using `<ngx-lil-gui />`, `<ngx-lil-gui [config] />`, |
| 68 | +or `<ngx-lil-gui [object] />` but never `<ngx-lil-gui [config] [object] />` |
0 commit comments