0

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 ?

1
  • This looks like a good use case for a pipe. Commented May 26, 2017 at 8:24

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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>

3 Comments

Would I need to create a new file for the service and take the relevant code out of app.component.ts?
sure, method 'filterBy' should be moved to the service.
in case you need to extract some value of the method, you create another method in component, that calls "this.filter.filterBy", that will return the value you need.
1
@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
}

1 Comment

this is different from the below answer as we are using angular DI which should be used when using services which is to used in multiple components

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.