What sets apart "activate" from "ngOnInit"?

I came across this example on the Angular 2 Style Guide website.

In my implementation, I would invoke this.show(); within the ngOnInit method, whereas in the demonstration it is called in the activate method.

Could someone please explain the distinction between the activate and ngOnInit methods? Thank you

export class ToastComponent implements OnInit {
  // public properties
  message: string;
  title: string;

  // private fields
  private defaults = {
    title: '',
    message: 'May the Force be with You'
  };
  private toastElement: any;

  // public methods
  activate(message = this.defaults.message, title = this.defaults.title) {
    this.title = title;
    this.message = message;
    this.show();
  }
  ngOnInit() {
    this.toastElement = document.getElementById('toh-toast');
  }

  // private methods
  private hide() {
    this.toastElement.style.opacity = 0;
    window.setTimeout(() => this.toastElement.style.zIndex = 0, 400);
  }
  private show() {
    console.log(this.message);
    this.toastElement.style.opacity = 1;
    this.toastElement.style.zIndex = 9999;
    window.setTimeout(() => this.hide(), 2500);
  }
}

Answer №1

ngOnInit() is a crucial Angular lifecycle hook that executes once the component's inputs have been initialized for the first time, following the initial execution of ngOnChanges(). On the other hand, activate is a custom function and not automatically invoked by Angular. To utilize it, you must explicitly call it within your custom code.

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

Issue with the scoring algorithm using Angular and Spring Boot

Hello, I have created a scoring algorithm to calculate scores, but I encountered an error in "salaireNet". ERROR TypeError: Cannot read properties of null (reading 'salaireNet') at ScoringComponent.calculateScore (scoring.component.ts:33:55) ...

Error with declaring TypeScript class due to private variable

When defining a TypeScript class like this: export class myClass { constructor(public aVariable: number) {} private aPrivateVariable: number; } and trying to initialize it with the following code: let someVar: myClass[] = [{ aVariable: 3 }, { aV ...

Learn about Angular8's prototype inheritance when working with the Date object

In my search for a way to extend the Date prototype in Angular (Typescript), I stumbled upon a solution on GitHub that has proven to be effective. date.extensions.ts // DATE EXTENSIONS // ================ declare global { interface Date { addDa ...

Delete information based on its unique identifier

Currently, I am trying to remove data from a list but encountering a small issue with the following code. Component Code removeSelectedRows(){ console.log(this.selection.selected.map(item => item.userId)) const selectedRowIds = this.selection. ...

Navigating through a dictionary in React TypescriptWould you like to learn

Currently, I am delving into the world of React and TypeScript. Within my journey, I have stumbled upon a dictionary representing various departments, with employee data stored in arrays. type Department = { Emp_Id: number, Name: string, Age: n ...

Guidelines for creating a masterpage and details page layout in Angular 6

In my app.component.html file, I have the following code: <div style="text-align:center"> <h1> Welcome to {{ title }}! </h1> </div> <div> <p-menu [model]="items"></p-menu> </div> Below is the code ...

Using Angular 4 to populate a form and ensure it remains untouched

Designed an update form that is pre-populated with information. I am aiming for the button to be inactive until any changes are made within the form The form group utilizes valueChanges to detect when information has been modified However, even when I u ...

Angular dynamic array binding binds to multiple elements rather than just one

In my code, I am working with an array object structured as follows: let myArray=[ { "id":"100", "child1":[ {"id":"xx","Array":[]}, {"id":"yy","Array":[]}, {"id":"zz","Array":[]} ] }, { "id":"200", "child1":[ {"id":"xx","Array ...

How can I extract JSON data within the Ionic2 framework?

After making an AJAX post call to an API, I successfully received a JSON response. Here is the response: JSON Response: { "s": true, "m": { "i": 10, "n": "Apple Watch", "p": "14000" }} While testing my TypeScript code, I used an alert to display the J ...

Error: Trying to access 'items' property of an undefined variable leads to a TypeError

I am currently working on creating a webpage with Angular 8 that fetches data from a REST API in JSON format by passing the request ID. My goal is to display this data in an HTML table that I have created. However, I encountered the following error: Typ ...

Unable to retrieve user data during route navigation

In my Angular application, I have created a service called AuthService: export class AuthService { public currentUser: Subject<firebase.User> = new Subject(); public currentUserId: Subject<string> = new Subject(); constructor(pri ...

Utilizing external applications within Angular applications

I have the task of creating a user interface for clocker, a CLI-based issue time tracker. Clocker functions as a stand-alone node.js application without any programming interface. To begin tracking time for an issue labeled 123, the command would typically ...

Having T extend Record<string, any>, the keyof T does not return 'string' as a type

My goal is to achieve the following: type UserDataProps<FieldName extends keyof DataShape, DataShape extends Record<string, any>> = { id: string; value: DataShape[FieldName]; } const userDataBuilder = <FieldName extends keyof DataShape, ...

Is there a way to set a custom port number for an Angular application?

I am currently in the process of constructing an Angular application. The application is designed to communicate with a server via HttpClient. However, each time the application connects to the server, it utilizes a different port. I am interested in confi ...

The concept of overloaded function types in TypeScript

Is it possible to create an overloaded function type without specifying a concrete function? By examining the type of an overloaded function, it appears that using multiple call signatures on an interface or object type is the recommended approach: functi ...

Error in Cordova integration with Razorpay [RazorPayCheckout not found]

I'm encountering an issue where I'm getting a "RazorPayCheckout is not defined" error. I've searched on StackOverflow but couldn't find any helpful answers. Can someone please assist me with this? Thank you in advance. app.component.ht ...

Cutting-edge Angular2 modules

Starting a new Sails + Angular2 project has been quite the adventure for me. I followed the module configurations from a tutorial I found, but then realized they were different from those in Google's latest heroes tutorial. After encountering some npm ...

Issue with Angular4 select in dropdown not able to trigger onChange event

I am new to working with Angular 4 and I am currently in the process of building something. In my project, I have multiple components, one of which contains the following HTML code: <div class="row" style="border:1px solid black;"> <br> <d ...

Guide to accessing a menu through Long press or Right click in Angular2

I recently started experimenting with angular 2 and I am trying to figure out how to create a menu that opens with multiple options on both mobile and desktop devices. What I'm looking for is a way to trigger the opening of a menu when a long hold or ...

Sharing slices of data among feature modules in NgRx allows for improved scalability and organization

I'm a newcomer to the world of NgRx and I find myself with some inquiries regarding the proper way to organize the state within a Store. Currently, we are in the process of developing an internal CRM system using Angular to manage client information. ...