I'm working on an Angular4 project and I have created a filter on my app.component.ts which I'm currently using on my app.component.html.
<button (click)="filterBy('cars')">Cars</button>
This works fine in this file by I want to use this same filter on my nav.component.html but I'd like to avoid recreating the filter code again on the nav.component.ts.
Is there a way of using this filter on my nav.component.html from app.component.ts ?
Migrate your created filter code in some new .ts file. Import this file in your app.component and other components by using import {ClassName} from file.ts syntax and then easily implement it in your component html code
You can create service, for example "filter.service.ts". Good thing in service is - it will create only one instance. So you use less memory, and app is faster.
Then - you can include it to the parent module:
import { FilterService } from "some/filter.service.ts";
#NgModule({
declarations: [ AppComponent, NavComponent],
providers: [ FilterService ]
})
export class MyModule { }
And use in your components like this:
import { FilterService } from "some/filter.service.ts";
constructor(filter: FilterService) {
this.filter = filter;
}
And then your html:
<button (click)="filter.filterBy('cars')">Cars</button>
#Injectable()
export class Service{
//create all the logic here for all the things you want to be shared across compponents
}
call this in the component you want to use like
import {Service} from "../shared/service";
#Component({
selector: 'app-angular4'
})
export class Angular4Component implements OnInit {
constructor(private service:Service) {
// resuse all the methods
}
Related
I have done some research on the net, and I have figured out that the problem I am facing is that multiple instances of service are being created, and I want to avoid that. Can some one please look at my code and spot the change I need to make.
Second service that uses the primary service that is being duplicated.
export class SecondaryService {
constructor(private primarySvc: IPrimaryService){
this.primarySvc.someSubject.subscribe(() => {});
}
}
Primary Service (the one that is being duplicated)
export class PrimaryService {
someSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
constructor(){}
}
Primary Service Provider
#Injectable()
export class PrimaryServiceProvider extends PrimaryService {
constructor(){
super();
}
}
Secondary Service Provider
#Injectable()
export class SecondaryServiceProvider extends SecondaryService {
constructor(private PrimaryProvider: PrimaryServiceProvider){
super(PrimaryProvider);
}
}
app.module.ts
#NgModule({
declaration: [SecondaryComponent],
exports: [SecondaryComponent],
imports: [BrowserModule],
providers: [SecondaryServiceProvider, PrimaryServiceProvider ]
})
export class SearchModule{}
Now I am trying to use the component I made in a local environment which looks something like this:
app.module.ts
#NgModule({
declaration: [AppComponent, HomeComponent],
imports: [SearchModule, BrowserModule],
providers: [PrimaryServiceProvider, SecondaryServiceProvider],
bootstrap: [AppComponent]
})
export class AppModule{}
home.component.ts
export class HomeComponent {
constructor( primarySvc: PrimaryServiceProvider,
secondarySvc: SecondaryServiceProvider) {
this.primarySvc.someSubject.next(false);
}
}
Now I know for sure the Primary Service has two instances since someSubject is not in sync, and the subscribe in SecondarySvc is not fetching any values from home.component.ts
Please tell me where do i need to make the changes
Thanks!!
Answering my own Question:
The services were duplicated due to incorrect file path while importing. Windows lets you use case-insensitive file paths, which may create multiple instances for every time the module is used.
I think you are overengineering using the PrimaryServiceProvider and SecondaryServiceProvider services.
To create a singleton service just set providedIn: 'root' option in the Injectable decorator, like this:
#Injectable({ providedIn: 'root' })
export class SecondaryService {}
At last, be sure to not register a singleton service at any providers array.
Check out the official documentation about this here.
I want to use jquery and easypiechart js file's functions in typescript.
It doesn't work this way.
How to define these script what i specified in code as typescript ?
index.component.ts
import { Component, OnInit } from '#angular/core';
import * as $ from "../../../../../assets/plugins/jquery/jquery.min.js";
import { easyPieChart } from "../../../../../assets/plugins/easypiechart/jquery.easypiechart.min.js";
// these above 2 js files are defined in angular.json script section
#Component({
selector: 'app-index',
templateUrl: './index.component.html',
styleUrls: ['./index.component.scss']
})
export class IndexComponent implements OnInit {
constructor() {}
ngOnInit() {
//$(function(){
// $('.easypiechart').easyPieChart();
//});
// How to write this above script as typescript ?????????????????????
}
}
From the above question,it looks like jquery.easypiechart.min.js is the one that you need to use in your angular application as external js.
Put the js under assets folder say /assets/js/jquery.easypiechart.min.js
Goto your projects angular.json file and under scripts node of architect node put as an entry in the array.
"scripts": [
"./node_modules/jquery/dist/jquery.min.js",
"./src/assets/js/jquery.easypiechart.min.js" ]
Now you can refer the external js in any of your projects components
declare var $: any;// referencing jQuery library
#Component({
selector: 'app-index',
templateUrl: './index.component.html',
styleUrls: ['./index.component.scss']
})
export class IndexComponent implements OnInit {
constructor() {}
ngOnInit() {
$(document).ready(function () {
//accessing easypiechart.min.js.
$('.easypiechart').easyPieChart();
});
}
}
If you have included them in the scripts or index.html, you don't have to import them to the .TS file again
Use declare instead and it should work
What does 'declare' do in 'export declare class Actions'?
Instead of putting it in asset folder you should use it as node_modules dependency
For easy pie chart run this npm i easy-pie-chart --save & for jquery run npm i jquery
Normally you don't want to use jquery in Angular, because it usually implies to modify directly the DOM, which is a bad practice, but there is the way to do it: https://medium.com/all-is-web/angular-5-using-jquery-plugins-5edf4e642969
If you wanna plot a pie chart or other types of charts, you could use ng2-charts instead, it will allow you to use charts.js with Angular and Typescript.
https://angular.io/guide/architecture#services
I'm following the docs on angular.io to inject dependencies like services, etc. I did everything they said and when I try to run it, the console keeps telling me:
Uncaught ReferenceError: LedgerService is not defined
I am doing nothing crazy except creating a simple component with a service where both constructors have console.log commands (constructors in both the component and service). I've done everything Angular says to do in their 2 paragraphs that details this feature of Angular.
The component itself is being injected into the main app module (with the service being injected into the component) and both the component and service were created with the Angular CLI. So there isn't much I've even done at all minus trying to inject the service. So I'm not sure where it is going wrong but it is definitely not working and just shows a blank page (when it previously had basic content by default).
I created both units, tried to specify providers in both the app.module and the component.ts file and neither works and yields the same error--when Angular claims either could work. I've also specified it as a private service within the constructor of the component.ts file.
Everything I've seen relating to this is always for Angular 1 or 2. Neither of which are even remotely similar to Angular 4/5.
If you really want to see this code, fine but it's literally just framework and nothing else:
bookkeeper.component.ts:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-bookkeeper',
templateUrl: './bookkeeper.component.html',
styleUrls: ['./bookkeeper.component.css'],
providers: [LedgerServiceService]
})
export class BookkeeperComponent implements OnInit {
constructor(private service: LedgerServiceService) { }
ngOnInit() {
console.log("Ledger component works!");
}
}
app.module.ts:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { InterfaceComponent } from './interface/interface.component';
import { BookkeeperComponent } from './bookkeeper/bookkeeper.component';
#NgModule({
declarations: [
AppComponent,
InterfaceComponent,
BookkeeperComponent
],
imports: [
BrowserModule
],
providers: [
LedgerServiceService
],
bootstrap: [AppComponent]
})
export class AppModule { }
ledger-service.service.ts:
import { Injectable } from '#angular/core';
#Injectable()
export class LedgerServiceService {
constructor() {
console.log("wtf");
}
}
LedgerService is actually called LedgerServiceService because I initially created LedgerService manually and then tried to use the AngularCLI to generate a service and named it LedgerService and it created a service called LedgerServiceService. Naming is not what is wrong. I only initially called it simply LedgerService because I figured it would be confusing.
Your examples are missing the import.
Anywhere we use a custom type, we also need to import that type.
For that reason, in both the module and component you will need to add:
import { LedgerServiceService } from './your-path-here'
You can see this in the examples they give on https://angular.io/guide/dependency-injection
I am looking for how to add html which is a return of the web service, in angular. The problem is that the angular directives do not rendered. here is my source code
//tohtml.directive.ts
import { Directive, ElementRef, OnInit } from '#angular/core';
#Directive({
selector: '[appToHtml]'
})
export class ToHtmlDirective {
constructor( private el: ElementRef) {}
tohtml() {
//it is assumed that this is the return of the webservice
this.el.nativeElement.innerHTML = '<a
[routerLink]="/link/to/page">helpful!
</a>';
}
}
Code for component.html
<div id="wrapper">
<h1 appToHtml>
Hello World!
</h1>
</div>
the code works, but the rendering of the [routerLink] does not work, pleaseee hellppp !!!
By setting innerHTML prop in your directive you only set DOM and attributes. But this content need to be compile by angular to allow angular-like behavior (binding directives, instanciating components etc..) .
Angular dont have compiler ready to use like angularJS ( which has $compile ). You need to use 3rd party libraries like
https://www.npmjs.com/package/p3x-angular-compile
or
https://www.npmjs.com/package/ngx-dynamic-template
Those lib comes with handy examples. You should easily understand how to use them.
Be aware that you cant use AOT with such a rendering system.
Edition for ngx-dynamic-template usage :
if your dynamic templates need some directive of component, you have to configure ngx-dynamic-template to import the corresponding modules.
You can create a dynamic module like that in your case
#NgModule({
imports: [
RouterModule
],
exports: [
RouterModule
]
})
export class DynamicModule {}
and then when importing ngx in your appModule or SharedModule
#NgModule({
imports: [
...
NgxDynamicTemplateModule.forRoot({extraModules: [DynamicModule]})
...
],
Then you will be able to use routerLink without problem (i just tested)
in cmpt :
htmlTemplate = `<a [routerLink]="['dress-options']">link to user component</a>`;
in template :
<div dynamic-template [template]="htmlTemplate"></div>
With the latest angular version for me only this module works fine: https://www.npmjs.com/package/ngx-dynamic-template
v2.1.24 for angular4, v.2.3.0 is for angular5
In the below code from ../src/app/app.module.ts,
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
Component consists:
view(../src/app/app.component.html)
logic(../src/app/app.component.ts)
style(../src/app/app.component.css)
Angular application is a tree of components. Good components have high cohesion, i.e. each component contains only elements with related functionality. They are also well encapsulated and loosely coupled.
How modules are different from components?
A component is just a class with the #Component() annotation. Note that .html and .css files might be referenced by the component, certainly not mandatory. The component template might very well be 'inlined' directly in the component configuration, or there simply might not be any html template at all for a given component.
A module is a structural element of an Angular application (and maybe other classes and interfaces). It is also "just a class" with the #NgModule() annotation.
It acts as a logical 'container' for your components, directives, services, pipes, etc... to help you structure your overall source code better.
You can have a look at this existing question : What's the difference between an Angular component and module
A module is something that has components. It wraps them up so you can import and manage them.
Notice when you make a component you can put anything that's decorated as #Injectable in your constructor:
#Component({
selector: 'app-heroes',
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
constructor(private myService: MyService) { }
ngOnInit() {
}
}
And magically you will have a myService to use. This is dependency injection, which is built into Angular - but it's managed on a Module level. In your module you import what other modules you want to be able to use:
imports: [
BrowserModule,
FormsModule
],
define what your module includes:
declarations: [
AppComponent,
HeroesComponent,
MyService
],
export any components (so other modules can import them)
exports: [
HeroesComponent
],
They help organize an application into blocks of functionality. Components are things that tell angular how to render something. Modules compose Components, Pipes, Services etc into 'blocks' that can be compiled by angular or imported and used by others.
Edit to address comment
Taking your specific question about HttpClient. The HttpClient is the service you are using to perform the actions. The HttpClientModule is the module you import into your module, so you can use the service it contains.
You import the module:
#NgModule({
imports: [
BrowserModule,
// Include it under 'imports' in your application module
// after BrowserModule.
HttpClientModule,
],
})
And use the service:
#Component(...)
export class MyComponent implements OnInit {
// Inject HttpClient into your component or service.
constructor(private http: HttpClient) {}
...
}
The HttpClientModule contains within it all you need for the HttpClient to work, and packages it up so you can use it in your own projects.
This particular module only wraps up that one service, but the module could contain a bunch of related services, components, pipes or directives. For example, the RouterModule allows you to use the RouterOutlet and RouterLink directives.
Module in angular is set of Components, Services, Filters, or some another smaller modules too, or we can say where you import all these in order to use later in the app for future use. in a single app there can be one or more than one module may exist.
Whereas, A component controls a patch of screen called a view.
You define a component's application logic—what it does to support the view—inside a class. The class interacts with the view through an API of properties and methods.
Refer this guide for more details:
https://angular.io/guide/architecture