我正在尝试在自定义指令中传递变量。但是加载后这会变得错误或未定义。请帮助我找到问题并指导我哪里错了。
自定义指令
import { Directive, ElementRef, Renderer2, AfterViewInit, Input, OnInit } from '@angular/core';
@Directive({
selector: '[air-btn]'
})
export class AirBtnDirective implements OnInit {
@Input() small?: boolean;
@Input() outline?: boolean;
constructor(private el: ElementRef, private renderer: Renderer2) { }
classes: string[] = [
'relative',
'disabled:opacity-70',
'disabled:cursor-not-allowed',
'rounded-lg',
'hover:opacity-80',
'transition',
'w-full',
this.outline ? 'bg-white' : 'bg-rose-500',
this.outline ? 'border-black' : 'border-rose-500',
this.outline ? 'text-black' : 'text-white',
this.small ? 'text-sm' : 'text-md',
this.small ? 'py-1' : 'py-3',
this.small ? 'py-1' : 'py-3',
this.small ? 'font-light' : 'font-semibold',
this.small ? 'border-[1px]' : 'border-2'
]
ngOnInit(): void {
console.log(this.outline)
this.classes.forEach((val) => {
this.renderer.addClass(this.el.nativeElement, val);
})
}
}
HTML
<button air-btn [outline]="true">Continue with Google</button>
任何解决方案表示赞赏!
您应该在 ngOnInit 中初始化类数组。
import { Directive, ElementRef, Input, OnInit, Renderer2 } from '@angular/core';
@Directive({
selector: '[air-btn]'
})
export class AirBtnDirective implements OnInit {
@Input() small?: boolean;
@Input() outline?: boolean;
constructor(private el: ElementRef, private renderer: Renderer2) {}
classes: string[] = [];
ngOnInit(): void {
this.classes = [
'relative',
'disabled:opacity-70',
'disabled:cursor-not-allowed',
'rounded-lg',
'hover:opacity-80',
'transition',
'w-full',
this.outline ? 'bg-white' : 'bg-rose-500',
this.outline ? 'border-black' : 'border-rose-500',
this.outline ? 'text-black' : 'text-white',
this.small ? 'text-sm' : 'text-md',
this.small ? 'py-1' : 'py-3',
this.small ? 'py-1' : 'py-3',
this.small ? 'font-light' : 'font-semibold',
this.small ? 'border-[1px]' : 'border-2',
];
console.log(this.outline);
this.classes.forEach((val) => {
this.renderer.addClass(this.el.nativeElement, val);
});
}
}