How to bring in classes and external libraries in Angular 2?

When importing an external class in TypeScript from another class, do I need to create a new instance of the variable before using it inside another class? For example, should I do let cli = new client()? Some tutorials barely mention this step and simply import and use it directly. Can you please provide some clarification on this? Thank you.

Thanks

Answer №1

It all comes down to what you are bringing into your project...

If you're importing a CLASS ... the answer is YES .. here's an example:

export class User{

public name:string;
public surname:string;
}

then in another ts file:

import { User } from '../../User';

let user= new User();
user.name= 'Fred';
user.surname = 'Scamuzzi';

IF you're importing an INTERFACE .. then it's a NO:

for instance

import {  OnInit } from '@angular/core';
  import { User } from '../../User';

export class AppComponent implements OnInit { // --> it requires you to implement the method declared in OnInit interface


ngOnInit(): void { // implemented

        let currentUser = new User();
    }

}

Similarly, when importing a Component in NgModule for declaration, you can simply do:

import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import {AuthService} from './shared/services/AuthService.service';

@NgModule({
    imports: [
        BrowserModule,

        HttpClientModule
    ],
    declarations: [
        AppComponent

    ],
    providers: [

        AuthService

    ],

    bootstrap: [AppComponent]
})
export class AppModule {

}

I trust this clarifies things for you ....

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

Tips for modifying a static property in TypeScript

I am currently developing a class that wraps around a WebSocket to function as an ingestor. After successfully setting up the ingestion process and passing a function to the class instance for processing incoming messages, I encountered an issue. I need t ...

Exploring the world of Jasmine and Angular: How to effectively mock nested methods within the Class being tested

Hello esteemed community... I have encountered a perplexing issue that appears straightforward, but has eluded my attempts at resolution... The challenge I am facing involves testing a Controller-Class in Angular. This particular codebase is laden with d ...

Manually initiating event broadcasts in Angular 5

After researching, I discovered a solution for implementing $broadcast and $on in Angular 5. It involves creating a custom service called broadcaster. I have two parallel components that need to listen for change events triggered by the parent component. ...

What is the most efficient way to use map-reduce in TypeScript to filter a list based on the maximum value of an attribute?

Recently, I came across a list that looked something like this: let scores = [{name: "A", skills: 50, result: 80}, {name: "B", skills: 40, result: 90}, {name: "C", skills: 60, result: 60}, {name: "D", skills: 60, ...

Deactivate multiple input fields by utilizing various radio buttons

I need help with enabling and disabling input fields based on radio button selection. When the first radio button is selected, I want to disable three input fields, when the second is selected, only two specific input fields should be enabled (SHIFT START ...

Utilize useEffect to track a single property that relies on the values of several other properties

Below is a snippet of code: const MyComponent: React.FC<MyComponentProps> = ({ trackMyChanges, iChangeEverySecond }) => { // React Hook useEffect has missing dependencies: 'iChangeEverySecond' useEffect(() => { ...

Unable to transmit props while employing Typescript in ReactJS

Attempting to pass props from components like AllProducts, MenProducts, etc. to the AddToCartButton component for reusability presents a challenge. When trying to pass props using: <AddToCartButton id={product.id} /> An error is encountered: Type & ...

NgFor in IONIC4 can only bind to Iterables like Arrays

Hello everyone, I am facing an issue in my code: it is displaying the error: (ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.) I am trying ...

Troubleshooting: Bootstrap not functioning in Angular with Webpack due to vendor bundle issue

Bootstrap is included in my vendor.js bundle, as shown in the snapshot below, https://i.stack.imgur.com/q5k8c.png Upon inspecting the DOM, it's clear that bootstrap classes are being applied too, as seen in the snapshot below, https://i.stack.imgur. ...

What could be causing TypeScript to raise an issue when a /// reference comes after the 'use strict' statement?

This particular inquiry is somewhat connected to a question I posted on Stack Overflow yesterday about why TypeScript is encountering issues when trying to import a module. The initial configuration remains unchanged. My TypeScript file appears as follows ...

Tips for implementing an automatic refresh functionality in Angular

I am dealing with 3 files: model.ts, modal.html, and modal.ts. I want the auto refresh feature to only happen when the modal is open and stop when it is closed. The modal displays continuous information. modal.htlm : <button class="btn btn-success ...

Troubleshooting the lack of success in enhancing global scope within Typescript

Currently, I am working on a microservices application where I have two very similar services that use practically the same packages. To perform some testing, I decided to add a function to the global scope and modified it slightly to prevent any TypeScrip ...

Avoid allowing generic types to be overwritten in Typescript

Is there a way to ensure that the layoutKey remains as type L (specifically IOfficialLevelLayouts) even when passing in other values? Every time I provide a value, it seems to override the desired type. https://i.sstatic.net/YfH6k.png https://i.sstatic.ne ...

Tips for using a loop variable as an argument in a method call for an attribute reference

Within the html code of my component, I have the following: <div *ngFor="let image of images; let i=index;" class="m-image-wrapper"> <i class="fa fa-times m-delete-img" (click)="removeImage(i, {{image.docname ...

Display or conceal elements in Angular based on multiple conditions

Looking to develop a functionality where an array of objects can be shown or hidden based on specific filters. The desired output should be as follows: HTML CODE: Filter: <div (click)="filter(1)"> F1 </div> <di ...

Ensure that selecting one checkbox does not automatically select the entire group of checkboxes

Here is the code I'm using to populate a list of checkboxes. <label class="checkbox-inline" ng-repeat="item in vm.ItemList track by item.id"> <input type="checkbox" name="item_{{item.id}}" ng-value="{{item.id}}" ng-model="vm.selectedItem" /& ...

Angular routing is giving me trouble when trying to open various menus at the same location

I am new to Angular and facing a situation where my HomeComponent has a reference to the Appmenucomponent in its .html page. I need to be able to click on different menus (each leading to a new component) and have them open in the same place (div), similar ...

What is the best way to send parameters from an Angular application to a Node.js API?

How can I correctly pass the id from Angular to my "/rating" HTTP endpoint? This is the method I am currently using: apiUpdateRating(id){ return this.http.get('http://localhost:8080/rating', { params:id }); } When ...

Saving files to MinIO from an Angular2 web form

I am currently working on a prototype for an Angular8 application that is capable of uploading files from a form to MinIO. Below is the structure of the form: upload-form.component.html : <input class="form-control" type="file" (change)="onFileCha ...

Would it be secure to store the Express Session Secret as plain text while using it with Angular inside a Docker Container?

Upon taking over a new project, I noticed that the front end docker container has been set up in the following manner. Although this may seem like a basic question, I am still getting the hang of working with Angular/Express/Nodejs. FROM node:18.12.1 ...