0

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 like ngIf
  • ng-condition component must have ng-if and ng-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:

  1. check if a ng-if is present (and only one is available) otherwise raise an exception;
  2. if a ng-if is visible (ng-if *ngCondition is true) all ng-else-if and ng-else are destroyed;
  3. if a ng-else-if is visible, the ng-else is destroyed;
  4. Only one ng-else is avalable, otherwaise an exception is raised;
  5. ng-if, ng-else-if and ng-else only can be placed into ng-condition;
  6. ng-if, ng-else-if must have a *ngCondition directive otherwaise an exception is raised;
  7. 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:

  1. How detect change of <ng-content></ng-content> and retrive all the child components?
  2. 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

Simone Nigro
  • 4,717
  • 2
  • 37
  • 72

0 Answers0