I'm new to Angular, just a question on use @Attribute in attribute directives, below is some code from a book:
@Directive({
selector: "[pa-attr]",
})
export class PaAttrDirective {
constructor(element: ElementRef, @Attribute("pa-attr") bgClass: string) {
element.nativeElement.classList.add(bgClass || "bg-success", "text-white");
}
}
and the template.html:
...
<td pa-attr="bg-warning">{{item.category}}</td>
...
so we can see that use @Attribute we can get the value of the attribute, but if we use data-binding attribute directive as:
<td [pa-attr]="item.category == 'Soccer' ? 'bg-info' : null">...
then the book modify the code as:
export class PaAttrDirective {
constructor(private element: ElementRef) {}
@Input("pa-attr")
bgClass: string;
ngOnInit() {
this.element.nativeElement.classList.add(this.bgClass || "bg-success", "text-white");
}
}
I'm a little bit confused here, can't we use @Attribute to get the value again as:
export class PaAttrDirective {
constructor(element: ElementRef, @Attribute("pa-attr") bgClass: string) {
element.nativeElement.classList.add(bgClass || "bg-success", "text-white");
}
}
why when use the attribute directive with data-binding then we have to create input property in the code and not able to use @Attribute?