Amal Shalika
Amal Shalika

Reputation: 1267

How to call Angular Component Method Outside of Angular Library using @ViewChild()?

I have angular library with expose component call AComponent. AComponent has template and set of method and properties. Once angular library is package it is expose as nuget package so other projects can be used it.

@Component({
  selector: 'xxx-editor',
  templateUrl: './xxx.component.html',
  styleUrls: ['./xxx.component.scss'],
})
export class AComponent implements OnInit {
......
......

 logToConsole() {
        console.log('trace for working');
 }

}

I have a new requirement so for cater that requirement I want to expose one of the method logToConsole in AComponent to outside so relying party can call the method using the component.

Will say this library is used by BComponent and access as ViewChild inside *.ts file

BComponent - Template

 <div style="text-align:center">
      <h1>
        Welcome to {{ title }}!
      </h1>
      <xxx-editor #xxxEditor [(ngModel)]="html" [editable]="true"
                        ></xxx-editor>

    </div>

BComponent - Ts

 @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
      ngOnInit(): void {
        this.editor.logToConsole();
      }
      title = 'editor-test';

      html = 'sample test data';

      @ViewChild('xxxEditor') editor: AComponent | null;
    }

Problem is this.editor.logToConsole() logToConsole is undefined. Is it how design angular library? Is there anyway I can access this method?

Upvotes: 0

Views: 1022

Answers (1)

Nithya Rajan
Nithya Rajan

Reputation: 4884

It's because the ngOnInit() life cycle method gets invoked before angular renders the DOM. You should call that method inside ngAfterViewInit() which gets invoked once the view is rendered.

ngAfterViewInit(): void {
   this.editor.logToConsole();
}

Angular Docs - Description

ngOnInit

Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties.

ngAfterViewInit

Respond after Angular initializes the component's views and child views / the view that a directive is in.

Upvotes: 4

Related Questions