Is there a way to execute the run function of a different Component in Angular 7 without causing the current

Is there a way to execute the ngOnInit() function from one component inside another component without needing to refresh the existing page?

Answer №1

Code snippet showcasing CompOneComponent functionalities

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-comp-one',
  templateUrl: './comp-one.component.html',
  styleUrls: ['./comp-one.component.css']
 })

export class CompOneComponent implements OnInit {

 constructor() { }

 ngOnInit() {
     console.log("CompOneComponent successfully initialized ..");
  }

 public compOneCall() {
    console.log("CompOneComponent function executed successfully ..");
  }
}

Example code for parent component - AppComponent

import { Component, OnInit } from '@angular/core';
import { CompOneComponent } from './comp-one/comp-one.component';

@Component({
 selector: 'my-app',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css'],
 providers: [CompOneComponent],
})

export class AppComponent implements OnInit {
public name = 'Angular 6';

constructor(private compOne: CompOneComponent) { }

ngOnInit() {
 this.compOne.ngOnInit();
 this.compOne.compOneCall();
 }
}

Check out this StackBlitz demo https://stackblitz.com/edit/hello-angular-6-tbufva,

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 strategies can I use to steer clear of the pyramid of doom when using chains in fp-ts?

There are times when I encounter a scenario where I must perform multiple operations in sequence. If each operation relies solely on data from the previous step, then it's simple with something like pipe(startingData, TE.chain(op1), TE.chain(op2), TE. ...

Changing Angular Material datepicker format post form submission

After selecting a date, the input field is populated with a format like DD/MM/YYYY Now, when attempting to send this data through a form and logging it in my component, datapicker.component.ts onFindAWhip(form: NgForm){ const value = form.value; ...

Can we establish communication between the backend and frontend in React JS by utilizing localstorage?

Trying to implement affiliate functionality on my eCommerce platform. The idea is that users who generate links will receive a commission if someone makes a purchase through those links. However, the challenge I'm facing is that I can't store the ...

What is the best way to remove a polygon from an agm-map?

Is there a way to remove a polygon from the map when the clear button is clicked? <agm-map [latitude]="40.034989" [longitude]="29.062844" [zoom]="15" [agmDrawingManager]="drawing" class="full-width-height"> ...

Showing error messages in Angular when a form is submitted and found to be invalid

My form currently displays an error message under each field if left empty or invalid. However, I want to customize the behavior of the submit button when the form is invalid. <form #projectForm="ngForm" (ngSubmit)="onSubmit()"> ...

Angular 2 Demonstrate Concealing and Revealing an Element

I am currently facing an issue with toggling the visibility of an element based on a boolean variable in Angular 2. Below is the code snippet for showing and hiding the div: <div *ngIf="edited==true" class="alert alert-success alert-dismissible fade i ...

Strategies for effectively mocking an Angular service: During Karma Jasmine testing, ensure that the spy on service.getShipPhotos is expected to be called once. In the test, it should

Currently, I am working on testing a function called getSingleShip in Angular 12 using Karma-Jasmine 4. The aim is to verify if this function is being called by another function named retrieveShip. However, the test results indicate that getSingleShip has ...

When retrieving objects using Angular's HttpClient, properties may be null or empty

I am working with a service class in Angular that utilizes the HttpClient to retrieve data from a web service. The web service responds with a JSON object structured like this: { "id": "some type of user id", "name": "The name of the user", "permiss ...

typescript leaflet loading tutorial

I'm attempting to replicate the basic example of loading a map with Leaflet in TypeScript, following the guidance on the Leaflet website. I am not utilizing any frameworks like Angular or React. I have installed Leaflet and types through npm. To adher ...

Issue encountered while attempting to remove a post from my Next.js application utilizing Prisma and Zod

Currently, I'm immersed in a Next.js project where the main goal is to eliminate a post by its unique id. To carry out this task efficiently, I make use of Prisma as my ORM and Zod for data validation. The crux of the operation involves the client-sid ...

How can I effectively utilize the Angular router to share routes among various named outlets?

My application requires displaying the same components or routes in multiple areas of the interface. This means allowing users to show certain components in various locations based on their selection, such as side panels or bottom right panels. In my situ ...

Guide to importing a class property from one file to another - Using Vue with Typescript

Here is the code from the src/middlewares/auth.ts file: import { Vue } from 'vue-property-decorator' export default class AuthGuard extends Vue { public guest(to: any, from: any, next: any): void { if (this.$store.state.authenticated) { ...

Can someone explain the inner workings of the Typescript property decorator?

I was recently exploring Typescript property decorators, and I encountered some unexpected behavior in the following code: function dec(hasRole: boolean) { return function (target: any, propertyName: string) { let val = target[propertyName]; ...

Discovering an Akita feature where Angular's select query gracefully handles the

Currently, I am exploring alternatives to NgRx, and Akita seems like a promising option. However, I am facing challenges with error management. There are times when I want an error to be handled at the app level, while in other cases, I prefer it to be man ...

Unable to start an expo project in bare workflow using TypeScript

Can someone help me with setting up an expo bare workflow using TypeScript? I ran the command "expo init [project name]" in my terminal, but I can't seem to find the minimal (TypeScript) option. ? Choose a template: » - Use arrow-keys. Return to sub ...

What is the method to retrieve the data type of the initial element within an array?

Within my array, there are different types of items: const x = ['y', 2, true]; I am trying to determine the type of the first element (which is a string in this case because 'y' is a string). I experimented with 3 approaches: I rec ...

What is the best way to apply a consistent set of values when altering fields conditionally in dynamically generated fields within Angular?

I just finished developing a dynamic row that consists of 2 dropdowns and a text field. Users have the ability to add or remove additional rows as needed. There is a specific condition in place: if the first dropdown value is 'Date' and the seco ...

Why is there always a reference to the previous data every time I create a new component?

I am currently working on a component that retrieves data from a service through an event message: this.objectDetailsSubscription = this.eventService.subscribe( EventsChannels.OBJECT_DETAILS, semantic => { this.layer = this.layerSem ...

Extracting PNG file from response (bypassing standard JSON extraction)

Despite my efforts to find a solution, I am still unable to resolve this specific issue: I have implemented an Angular request (localhost:4200) to an API on Spring (localhost:8080). The HttpService successfully handles the requests, except when it comes to ...

How to set an attribute within ngFor in Angular 2

Encountering an issue trying to dynamically set the selected attribute within an ngFor loop. The current code is not working as expected due to browser quirks where even checked=false would still be considered as checked... Hence, the return value must be ...