Skip to content

Commit

Permalink
[Angular] Migrate to signal (password-strength-bar component)
Browse files Browse the repository at this point in the history
  • Loading branch information
qmonmert committed Jan 11, 2025
1 parent c4e8127 commit e08a35b
Showing 1 changed file with 24 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
See the License for the specific language governing permissions and
limitations under the License.
-%>
import { Component, ElementRef, inject, Input, Renderer2 } from '@angular/core';
import { Component, ElementRef, Renderer2, effect, inject, input } from '@angular/core';

import SharedModule from 'app/shared/shared.module';

Expand All @@ -27,11 +27,34 @@ import SharedModule from 'app/shared/shared.module';
styleUrl: './password-strength-bar.component.scss',
})
export default class PasswordStrengthBarComponent {
passwordToCheck = input<string>('');

colors = ['#F00', '#F90', '#FF0', '#9F0', '#0F0'];

private readonly renderer = inject(Renderer2);
private readonly elementRef = inject(ElementRef);

constructor() {
effect(() => {
const password = this.passwordToCheck();
if (password) {
const c = this.getColor(this.measureStrength(password));
const element = this.elementRef.nativeElement;
if (element.className) {
this.renderer.removeClass(element, element.className);
}
const lis = element.getElementsByTagName('li');
for (let i = 0; i < lis.length; i++) {
if (i < c.idx) {
this.renderer.setStyle(lis[i], 'backgroundColor', c.color);
} else {
this.renderer.setStyle(lis[i], 'backgroundColor', '#DDD');
}
}
}
});
}

measureStrength(p: string): number {
let force = 0;
const regex = /[$-/:-?{-~!"^_`[\]]/g; // "
Expand Down Expand Up @@ -72,23 +95,4 @@ export default class PasswordStrengthBarComponent {
}
return { idx: idx + 1, color: this.colors[idx] };
}

@Input()
set passwordToCheck(password: string) {
if (password) {
const c = this.getColor(this.measureStrength(password));
const element = this.elementRef.nativeElement;
if (element.className) {
this.renderer.removeClass(element, element.className);
}
const lis = element.getElementsByTagName('li');
for (let i = 0; i < lis.length; i++) {
if (i < c.idx) {
this.renderer.setStyle(lis[i], 'backgroundColor', c.color);
} else {
this.renderer.setStyle(lis[i], 'backgroundColor', '#DDD');
}
}
}
}
}

0 comments on commit e08a35b

Please sign in to comment.