Angular ng-template : Access method of the container template from within the invoked template?

Viewed 517

I have an originator template that refers the template its rendering. I have a method in the originating template which I want invoked in the child template (not sublassing the origin template component.ts in the reference component.ts because of some DI related reasons). How would I go about this?

originator.component.ts

export class OriginatorComponent implements OnInit {
.....
    execute() {
        // Execute some code
    }

    retrieve() {
        // Execute some code
    }
}

originator.component.html

<ng-container *ngIf="test === 'abc'">
    <ng-container *ngTemplateOutlet="abcdef"></ng-container>

    <ng-template #abcdef>
      <foo-template></foo-template>
    </ng-template>

foo.component.ts

@Component({
    selector: 'foo-component',
    templateUrl: './foo-component.component.html',
    styleUrls: ['./foo-component.component.scss']
})
export class FooComponent implements OnInit {
.....
    someMethod1() {
        execute();    // <--- HOW DO I DO THIS? EXECUTE Originating templates method?
    }

    someMethod2() {
        retrieve();    // <--- HOW DO I DO THIS? EXECUTE Originating templates method?
    }
}
2 Answers

I will suggest not trying to invoke the parent method in the child. Consider using an event emitter to communicate to the parent from the child https://angular.io/guide/component-interaction#parent-listens-for-child-event.

Originator Component:

export class OriginatorComponent implements OnInit {
    .....
    onExecute() {
        // Execute some code
    }
}

Originator Component Template:

<ng-container *ngIf="test === 'abc'">
  <ng-container *ngTemplateOutlet="abcdef"></ng-container>
</ng-container>

<ng-template #abcdef>
  <foo-template (execute)="onExecute()" ></foo-template>
</ng-template>

Foo Component

@Component({
   selector: 'foo-component',
   templateUrl: './foo-component.component.html',
   styleUrls: ['./foo-component.component.scss']
})
export class FooComponent implements OnInit {
    @Output() execute = new EventEmitter();
    .....
    someMethod() {
        this.execute.emit(); // you can send any variable to parent
    }
}

When this.execute.emit(); is fired, your handler in your parent element (onExecute) will be called.

EDIT

Here is a stackblitz demo

<ng-template #abcdef>
    <foo-component></foo-component>
</ng-template>

and in your component file use

@ViewChild(FooComponent  ) ref: FooComponent;

In ngAfterViewInit() { this.ref.someMethod1(); } is called.

Related