can i use eventEmeter in ng-container with *ngTemplateOutlet

22 Views Asked by At

Can I use output with EventEmitter to exchange events between a template and the parent component, like in this example:

<div>
   <ng-container
      *ngTemplateOutlet="
        field.field.editTemplate;
        context: {
          dataItem: field
        }
      "
      (validate)="validateField(field)"
    ></ng-container>
</div>

For example, the template code is:

<ng-template let-dataItem="dataItem" #EditTemplate>
  <div
    class="noselect"
    style="position: absolute; margin: 0px; height: 100%; width: 100%"
  >
    <input
      type="checkbox"
      [id]="'customCheckbox' + dataItem.id"
      [(ngModel)]="dataItem.isChecked"
      style="display: none"
    />
    <label
      [for]="'customCheckbox' + dataItem.id"
      (click)="onClic()"
    >
      <i
        *ngIf="dataItem.isChecked; else uncheckedIcon"
        style="cursor: pointer; color: forestgreen; font-size: 200%"
        class="material-icons icons-lg"
        >check_circle_outline</i
      >
      <ng-template #uncheckedIcon>
        <i
          placement="bottom"
          style="cursor: pointer; color: rgb(0, 110, 255); font-size: 200%"
          class="material-icons icons-lg"
          >check_circle_outline</i
        >
      </ng-template>
    </label>
  </div>
</ng-template>
onClic(){
   this.validate.emit(true)
}

I've done this, but the event doesn't transfer in the validateField(field) methode.

Can I use output with EventEmitter to exchange events between a template and the parent component

1

There are 1 best solutions below

0
Thomas Cayne On

Yes! The Angular EventEmitter must be used in a child component that contains the template. So you would define the EventEmitter like:

@Output() validate = new EventEmitter<boolean>();

Try not to use onClic as your function name. Make it more meaningful/readable like validateOnClick();

validateOnClick() {
   this.validate.emit(true); <---- should it always be TRUE?
}

In parent component:

validateField(field: any) {
   console.log('Validation triggered for field:', field);
}

Check out NgTemplateOutlet Type Checking here:

https://medium.com/@thomas.laforge/ngtemplateoutlet-type-checking-5d2dcb07a2c6