Ues setAttribute

This commit is contained in:
shamoon committed 2026-11-02 21:18:33 -08:00
1 parent 993db43d50
commit e0d6f27585
2 files changed
+20 -12

No files matched your search

@@ -30,6 +30,17 @@ describe('BootstrapIconComponent', () => {
expect(svg.getAttribute('height')).toEqual('2')
})
it('should not allow width or height to inject attributes', () => {
fixture.componentRef.setInput('name', 'x-lg')
fixture.componentRef.setInput('width', '1" onload="alert(1)')
fixture.componentRef.setInput('height', '1" onclick="alert(1)')
fixture.detectChanges()
const svg: SVGElement = fixture.nativeElement.querySelector('svg')
expect(svg.hasAttribute('onload')).toBe(false)
expect(svg.hasAttribute('onclick')).toBe(false)
expect(svg.getAttribute('width')).toEqual('1" onload="alert(1)')
})
it('should update when the name changes', () => {
fixture.componentRef.setInput('name', 'x-lg')
fixture.detectChanges()
@@ -8,8 +8,6 @@ import {
} from '@angular/core'
import { icons } from './icons'
const DEFAULT_SIZE = '16'
/** Converts icon name e.g. `arrow-down-up` to its registry key. */
const toKey = (name: string) =>
name.trim().replace(/-(.)/g, (_, char: string) => char.toUpperCase())
@@ -32,26 +30,25 @@ export class BootstrapIconComponent {
constructor() {
effect(() => {
this.elementRef.nativeElement.innerHTML = this.svg()
const element = this.elementRef.nativeElement
element.innerHTML = this.svg()
const svg = element.firstElementChild
if (!svg) return
const width = this.width()
const height = this.height()
if (width) svg.setAttribute('width', String(width))
if (height) svg.setAttribute('height', String(height))
})
}
private svg(): string {
const name = this.name()
if (!name) return ''
let svg = icons[toKey(name)]
const svg = icons[toKey(name)]
if (!svg) {
console.warn(`Icon not found: ${name}`)
return ''
}
const width = this.width()
const height = this.height()
if (width) {
svg = svg.replace(`width="${DEFAULT_SIZE}"`, `width="${width}"`)
}
if (height) {
svg = svg.replace(`height="${DEFAULT_SIZE}"`, `height="${height}"`)
}
return svg
}
}