I want simplify the built in directive ngIf; else with a custom component. The idea is eg.:
@Component({
selector: 'app-main',
template: `
<ng-condition>
<ng-if *ngCondition="number <= 5">
Number {{ number }} is minor or equal 5
</ngif>
<ng-else-if *ngCondition="number <= 10">
Number {{ number }} is minor or equal 10
</ng-else-if>
<ng-else>
Number {{ number }} is major of 10
</ng-else>
</ng-condition>`
})
export class AppComponent {
number = 6;
}
output
Number 6 is minor or equal 10
The idea is:
*ngConditiondirective is a custom directive likengIfng-conditioncomponent must haveng-ifandng-else-if,ng-elseis optional.
Components ng-if, ng-else-if and ng-else are just:
@Component({
selector: 'ng-if',
template: '<ng-content></ng-content>'
})
export class NgIf {}
@Component({
selector: 'ng-else-if',
template: '<ng-content></ng-content>'
})
export class NgElseIf {}
@Component({
selector: 'ng-else',
template: '<ng-content></ng-content>'
})
export class NgElse {}
*ngCondition directive is:
@Directive({
selector: '[ngCondition]'
})
export class NgConditionDirective {
constructor(
private element: ElementRef,
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef
) {}
@Input()
set ngCondition(val: boolean) {
if(val) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
}
The ng-condition is:
@Component({
selector: 'ng-condition',
template: '<ng-content></ng-content>'
})
export class NgCondition {
// ... HERE THE MAGIC CODE TO WRITE
}
The idea is, ng-condition component retrive all child component (ng-if, ng-else-if and ng-else) and:
- check if a
ng-ifis present (and only one is available) otherwise raise an exception; - if a
ng-ifis visible (ng-if *ngConditionis true) allng-else-ifandng-elseare destroyed; - if a
ng-else-ifis visible, theng-elseis destroyed; - Only one
ng-elseis avalable, otherwaise an exception is raised; ng-if,ng-else-ifandng-elseonly can be placed intong-condition;ng-if,ng-else-ifmust have a*ngConditiondirective otherwaise an exception is raised;ng-elsecan't have a*ngConditiondirective otherwaise an exception is raised;
The main problem is detect change of <ng-content></ng-content> into ng-condition componet and retrive all child component for write all the logic.
Final questions:
- How detect change of
<ng-content></ng-content>and retrive all the child components? - How check if a child component have a specific directive?
I'm also searching some inspiration, tips and trick for start to develop my idea.
Thanks!
UPDATE
I have developed my idea: https://www.npmjs.com/package/ng-condition