UtilUpdated in v16Optional

wrIsSafeCssValue

Answers whether a CSS value can be put inside a larger expression, such as a colour inside a linear-gradient() you build, without breaking out of its slot.

Installation

Import the class. This entry point has no stylesheet.

import { wrIsSafeCssValue } from 'ngwr/utils';

Usage

Check a value that comes from outside before you compose it. Fall back to your default when it fails: do not repair it.

import { computed, input } from '@angular/core';
import { wrIsSafeCssValue } from 'ngwr/utils';

readonly from = input('var(--wr-color-primary)');
readonly to = input('var(--wr-color-success)');

protected readonly background = computed(() => {
  const from = wrIsSafeCssValue(this.from()) ? this.from() : 'var(--wr-color-primary)';
  const to = wrIsSafeCssValue(this.to()) ? this.to() : 'var(--wr-color-success)';
  return `linear-gradient(90deg, ${from}, ${to})`;
});
ValueSafeWhy
var(--wr-color-primary)YesOne value, an allowed function.
color-mix(in srgb, red 50%, blue)YesThe commas are inside the function.
red 20%YesWhitespace is fine: a gradient stop.
red, blueNoA top-level comma reaches the next slot.
red), url(//x.test/a), linear-gradient(redNoA closing parenthesis it never opened.
url(//x.test/a)NoAn image function: it fetches.
red; position: fixedNoA semicolon ends the declaration.
  • A containment check, not a colour parser: a safe value can still be one no browser accepts.
  • Allowed functions: the colour functions, color-mix(), light-dark(), var(), calc(), min(), max() and clamp().
  • A value longer than 256 characters is refused.
  • A value bound straight to [style.background] needs no check: there is nothing to break out of.

API

NameDescriptionTypeDefault
wrIsSafeCssValuetrue when the value stays inside the slot it is composed into. false for an empty string and for anything that is not a string.(value: string) => boolean-

See also