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:
*ngCondition
directive is a custom directive likengIf
ng-condition
component must haveng-if
andng-else-if
,ng-else
is 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-if
is present (and only one is available) otherwise raise an exception; - if a
ng-if
is visible (ng-if *ngCondition
is true) allng-else-if
andng-else
are destroyed; - if a
ng-else-if
is visible, theng-else
is destroyed; - Only one
ng-else
is avalable, otherwaise an exception is raised; ng-if
,ng-else-if
andng-else
only can be placed intong-condition
;ng-if
,ng-else-if
must have a*ngCondition
directive otherwaise an exception is raised;ng-else
can't have a*ngCondition
directive 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