Friday, 18 March 2022

Angular Providers, add TitleCasePipe(pipes from angular/common) to component instead of just using as{{value |titlecase}} in html

 What is provider


https://medium.com/claritydesignsystem/making-full-use-of-angular-providers-part-1-14609a09514b#:~:text=A%20provider%20is%20an%20object,other%20classes%20instantiated%20by%20Angular.


provider is an object declared to Angular so that it can be injected in the constructor of your components, directives and other classes instantiated by Angular


All services in angular have default : 


@Injectable({

    providedIn: "root",

})


meaning they are being added to root module, (app.module.ts) in it's providers:[] as default, so it can be used in components of other modules by just 

import {ServiceA}, and instantiate in constructor like consturctor (private serviceA : ServiceA) {}


**Service is also a class, so for other classes to be used in certain components of a module, we need to add it in provider first.


For titlecase pip(class from angular/common) it can be used in html like 

https://stackoverflow.com/questions/49296458/capitalize-first-letter-of-a-string-using-angular-or-typescript

{{value |titlecase}}

For titlecase pipe to be used in component of a module, we need to add as provider in that module or add in root module so it can be used in any components of any module

https://medium.com/swlh/how-to-use-an-angular-pipe-in-a-component-file-82a0761bd7f9


To import in module:



import { TitleCasePipe } from '@angular/common';@NgModule({declarations: [AppComponent],
imports: [BrowserModule ],
providers: [TitleCasePipe],
bootstrap: [AppComponent]
})
export class AppModule { }


To use in a component :



import { Component, OnInit} from '@angular/core';
import { TitleCasePipe } from '@angular/common';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'pipe-in-component';
fullname = ''
constructor(private titleCasePipe: TitleCasePipe) {}ngOnInit(): void {
this.fullname = this.titleCasePipe.transform('keVin carTor')
}}






No comments:

Post a Comment