Unlock the power of Angular Component methods even when outside the Angular library with the help of @ViewChild()

In my Angular library, there is a component called AComponent which has its own template, methods, and properties. Once the Angular library is packaged, it becomes available as a NuGet package for other projects to utilize.

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

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

}

A new requirement has come up where I need to expose the method logToConsole in AComponent so that external parties can call this method using the component.

Let's say that this library is being used by BComponent and accessed as ViewChild inside the *.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;
    }

The issue arises when trying to access this.editor.logToConsole(). The error states that logToConsole is undefined. Is this how the Angular library is designed? Is there a way for me to access this method?

Answer №1

The reason is because the ngOnInit() life cycle method is triggered before angular renders the DOM. It would be best to call that method within the ngAfterViewInit() which is called once the view has been rendered.

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

Angular Docs - Explanation

ngOnInit

This function initializes the directive/component after Angular initially displays the data-bound properties and assigns the directive/component's input properties.

ngAfterViewInit

This function executes after Angular has initialized the views of the component including child views / the view in which a directive is placed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason my component is not displaying the ContentChild associated with a directive?

It appears that utilizing a directive to target a content child from another directive is the recommended approach (source). However, why isn't my component able to recognize the component marked with the directive? ./my.component.ts import { Comp ...

Issue encountered on IIS 7.x server during deployment with HTTPS

Currently, I am running an Angular + .Net 4.5 fullStack application on IIS V7.5 with Windows Server. To conduct additional tests, I am using multiple instances of the same site with different versions of the application deployed on the same host. Each inst ...

Strange data being received by Angular from ASP.NET API

I'm encountering some trouble with my ASP.NET API communicating with Angular, and I'm unsure of the root cause. I'm seeking assistance in reviewing my code for any glaring errors. Here is a snippet from my API Controller: // Data Structure ...

What steps do I need to take to create a customizable Angular Material NPM module?

Can a custom npm module be created using Angular Material that allows the components to be styled by the consuming app's unique theme? For instance, imagine an npm module with a component containing the following template: <button mat-raised-butt ...

Is there a way to modify the antd TimePicker to display hours from 00 to 99 instead of the usual 00 to 23 range?

import React, { useState } from "react"; import "./index.css"; import { TimePicker } from "antd"; import type { Dayjs } from "dayjs"; const format = "HH:mm"; const Clock: React.FC = () =& ...

Angular: Display the output of an InfluxDB API call

I have the InfluxDB API data that I need to present in a table using Angular, but I'm unsure if I should treat it as an object or an array. Does anyone have an example to help me with this? My Angular version is 9. Component: listaCBS_CPU ...

One server hosts several Angular applications on an IIS website

Is it possible to host multiple independent angular applications on a single IIS virtual directory? For instance: mysite.com/admin mysite.com/sales mysite.com/inventory The issue arises when hosting with folders as the URLs to inner pages do not ...

Oops! The type error is indicating that you tried to pass 'undefined' where a stream was required. Make sure to provide an Observable, Promise, Array, or Iterable when working with Angular Services

I've developed various services to interact with different APIs. The post services seem to be functioning, but an error keeps popping up: ERROR TypeError: You provided 'undefined' where a stream was expected. Options include Observable, ...

Constantly receiving an undefined value when trying to access a variable in an ngrx Observable

Here is the code snippet I am working with: language.component.ts form: FormGroup; first: AbstractControl; second: AbstractControl; constructor(private _fb: FormBuilder) { this.first = new FormControl('', [Validators.required, Va ...

A guide on incorporating Google authentication into Vue.js with the use of TypeScript and the component-based syntax

Currently, I am in the process of integrating Google authentication into my Vue.js front end. The project was initialized using CLI with TypeScript and component style syntax enabled, alongside other configurations. Additionally, there is a backend web ser ...

What is the syntax for creating a function with parameters of type `any` or `void` in TypeScript?

How can I create a function in typescript that accepts either something or nothing as input? I attempted the following: interface TestFn { (input: any | void): string } const operation: TestFn = (input) => 'result'; operation('some ...

Utilize the identical function within the reducer for numerous mat-slide-toggle and checkboxes in component.html

I'm currently diving into the world of Angular and ngrx while tackling a project focused on enabling users to create forms. In this project, users can add various form elements (such as labels, text fields, dropdown menus, checkboxes, etc.) from a sid ...

Using TypeScript to destructure arrays within a parameter list

As I delve into TypeScript, my focus is on mastering array destructuring within the arguments list. While object destructuring is feasible using this method: let foo = function({firstname, lastname}){...} foo({ firstname: 'ralph', lastname ...

When the child component's form is marked as dirty, the parent component can access it

I have implemented a feature in my application that notifies users about pending changes on a form before they navigate away. Everything works as expected, but I have a child component with its own form that needs to be accessed by the guard to check if i ...

A more efficient way to specify children types in Typescript React is by directly specifying the type in the function instead

What is the reason behind this: interface UserSidebarProps { children? : React.ReactNode } function UserSidebar({children}: UserSidebarProps) { return ( <div> {children} </div> ) } Why doesn't this work? function User ...

Guide on populating text boxes in a form automatically using ngFor?

As a beginner Angular developer, I am looking to automatically fill in text boxes in a form, specifically 10 text boxes (10 rows) using the ngFor directive. In my research on ngFor examples, I have noticed that most of them focus on populating a list base ...

Following the recent update to IntelliJ IDEA 2022.1.3, the use of ::ng-deep has been marked

After updating the version of IntelliJ, I noticed that the ::ng-deep angular material selector is now marked as deprecated. Here's an example: <mat-form-field class="register-custom-select"> <mat-select formControlName="gende ...

What is the approach to constructing an observable that triggers numerous observables depending on the preceding outcome?

One of my endpoints returns { ids: [1, 2, 3, 45] }, while the other endpoint provides values for a given id like { id: 3, value: 30, active: true }. I am currently attempting to create an observable that will call the first endpoint and then, for each id r ...

The CSS "mask" property is experiencing compatibility issues on Google Chrome

Hey there! I've recently developed a unique progress bar component in React that showcases a stunning gradient background. This effect is achieved by utilizing the CSS mask property. While everything runs smoothly on Firefox, I'm facing a slight ...

Issues persist with the implementation of async in Angular2+

In my Angular2+ component, I created a function that outputs the results before actually running the function. This causes the desired output to appear later than expected. The function sends a variable parameter with an HTTP request to a NodeJS backend an ...