Last active
August 14, 2020 21:56
-
-
Save umairhm/77f99ed74b64d2400f5413fd2301b8ad to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, Input } from '@angular/core'; | |
import { coerceCssPixelValue } from '@angular/cdk/coercion'; // NEW IMPORT | |
@Component({ | |
selector: 'css-pixel-coercion', | |
template: `...` | |
}) | |
export class CssPixelCoercionComponent { | |
// In the following code, `@Input paddingX` will NOT work with strict type checking | |
// But we'll make the `@Input paddingY` to work with strict type checking as well | |
// Declare private properties to hold coerced booleans | |
private _paddingX: string; | |
private _paddingY: string; | |
// We have to separate this getter and name it differently to be used in the template | |
// This works in combination with the `@Input set paddingY` defined on line 36 | |
get coercedPaddingY(): string { | |
return this._paddingY; | |
} | |
// Use setter to call coerceCssPixelValue method and convert passed values to pixel string | |
@Input() | |
get paddingX(): string { | |
return this._paddingX; | |
} | |
set paddingX(val: string) { | |
this._paddingX = coerceCssPixelValue(val); | |
} | |
// Note that the val parameter excepts value of type 'number | string' | |
// We have to do this for strict type checking to work properly | |
// If we don't do this, following error will be thrown: | |
// Type 'number' is not assignable to type 'string'. | |
@Input() | |
set paddingY(val: number | string) { // [A] More details in the article | |
this._paddingY = coerceCssPixelValue(val); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment