I am writing an Angular 5 directive, whose objective is adding some host views(created from a component) into the viewContainer.
My dilemma is that I don't know if I should use an attribute directive or a structural directive for this purpose. I've tried both, and they both work, so I need an explanation on which one I should use.
Attribute directive:
HTML:
<div [myAttrDirective]="param"></div>
Directive:
import {
Directive,
Input,
ViewContainerRef,
ComponentRef,
ComponentFactoryResolver,
} from "@angular/core";
import { MyComponent } from "./my-component";
@Directive({ selector: "[myAttrDirective]" })
export class AttrDirective {
@Input()
public set AttrDirective(attrDirective: any) {
const factory = this.componentFactoryResolver.resolveComponentFactory(
MyComponent,
);
attrDirective.forEach((element, index) => {
const componentRef: ComponentRef<
MyComponent
> = this.viewContainer.createComponent(factory);
const myComponent: MyComponent = componentRef.instance;
myComponent.setInformation({ element });
});
}
constructor(
private viewContainer: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver,
) {}
}
Structural directive:
HTML:
<div *myStrDirective="params"></div>
Directive:
import {
Directive,
Input,
ViewContainerRef,
ComponentRef,
ComponentFactoryResolver,
} from "@angular/core";
import { MyComponent } from "./my-component";
@Directive({ selector: "[myStrDirective]" })
export class StrDirective {
@Input()
public set StrDirective(strDirective: any) {
const factory = this.componentFactoryResolver.resolveComponentFactory(
MyComponent,
);
strDirective.forEach((element, index) => {
const componentRef: ComponentRef<
MyComponent
> = this.viewContainer.createComponent(factory);
const myComponent: MyComponent = componentRef.instance;
myComponent.setInformation({ element });
});
}
constructor(
private viewContainer: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver,
) {}
}
which one to use attribute directive or a structural directive ?
Answer is :
attribute directive - this directive used to change appearance or behavior of element with which it attached. Example : I want to add tooltip dynamically to my textbox control or color textbox and its parent based on condition. So it changing appearance or behavior of element in that case go for attribute directive as you want to interact with element with which directive is attached.
Structural directive - this directive used to change structure of html. For example *ngFor (which adds element in html), *ngIF (hide show element in html based on condition), in that case you can use structural directive.
In you case you are not changing div element but you are adding element in html structure , so you can create structure directive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With