Alexander Mills
Alexander Mills

Reputation: 100446

Instantiate Angular service via HTML call

Say we have this component:

@Component({

  template: `
   <div *ngFor="let v of values;" #aService="getServiceInstance()">
      <child-component1 [s]="aService"></child-component1>
      <child-component2 [s]="aService"></child-component2>
   </div>
 `

})
export class MyComponent {

  values = [1,2,3,4,5];

  getServiceInstance(){

      // ??? how to implement this ???

  }

}

my question is - how can I implement the getServiceInstance() method so that I inject a new service instance into the child-component? Is there a way to do that somehow? Maybe using a decorator?

I am guessing that something like this is possible:

 @Inject(MyService)
 getServiceInstance(ms: MyService){

    ms.13 = 'dangerous';
    return ms;

 }

but that's just a guess.

Upvotes: 0

Views: 525

Answers (2)

Igor
Igor

Reputation: 62298

Then you can create a complex object (instead of just a number) in the values array that contains a service and the number. Use a factory service to create an instance of a service per item in the array at the time the array is created/mutated (whatever). Then you can reference this service in the *ngFor loop in the template should you want to pass the service to the child component.

You would need to provide the implementations / definitions of Service and ServiceFactory but this should illustrate the point.

@Component({
  template: `
   <div *ngFor="let v of enrichedValues">
      <child-component1 [s]="v.service"></child-component1>
   </div>`
})
export class MyComponent implements OnInit {

  @Input()
  values = [1,2,3,4,5];

  enrichedValues: {value:number, service:Service}[];

  constructor(private serviceFactory: ServiceFactory){
  }

  ngOnInit(){
    this.enrichedValues = this.values.map(val => {value: val, service: this.serviceFactory.createService()});
  }
}

Upvotes: 2

Suren Srapyan
Suren Srapyan

Reputation: 68685

Why don't create that service as a separate service with @Injectable decorator and then inject that service in the child-component-s.

@Injectable()
export class YourService { ... }

...

@Component({...})
export class ChildCmp {
   constructor(private yourService: YourService)
}

You can do something like

getServiceInstance() {

   return () => {
      // Your logic here
   };

}

but I don't think this is a good solution cause I don't understand why you want to do things like that.

Upvotes: 1

Related Questions