Nguyen
Nguyen

Reputation: 423

How to plugin a Component in a Component other

I have a Component is A, it plugin to index.html, and it have template is:

<div> content of A </div>
<component-will-plugin></component-will-plugin>
<button (click)="pluginBtoA()">click me to plugin B to plugin A </button>

and code of function pluginBtoA:

pluginBtoA(){
  redirectToB;
}

How to plugin B Component in A Component when i click button?

Thank for read my question.

Upvotes: 1

Views: 327

Answers (2)

Angel Angel
Angel Angel

Reputation: 21756

This example is from the Angular2 IO page.

@Component({
  selector: 'child-component',
  template: 'Child'
})

class ChildComponent {
}

@Component({
  selector: 'my-app',
  template: 'Parent (<div #child></div>)'
})

class MyApp implements OnInit {
  constructor(private dcl: DynamicComponentLoader, private elementRef: ElementRef) {

  }

  ngOnInit(){
      this.dcl.loadIntoLocation(ChildComponent, this.elementRef, 'child');
  }
}

You can read about this https://angular.io/docs/ts/latest/api/core/DynamicComponentLoader-class.html#!#loadIntoLocation

Now you can move this this.dcl.loadIntoLocation(ChildComponent, this.elementRef, 'child'); within the calling function when you click

for example:

pluginBtoA(){
  //redirectToB;
  this.dcl.loadIntoLocation(ChildComponent, this.elementRef, 'child');
}

Upvotes: 2

Thierry Templier
Thierry Templier

Reputation: 202346

You could use the DynamicComponentLoader and its loadIntoLocation method this way:

@Component({
  selector: 'my-app',
  template: `
    Parent
    <div #child></div>
    <div (click)="onClick()">Add sub component</div>
  `
})
export class MyApp {
  constructor(private dcl: DynamicComponentLoader,
              private elementRef: ElementRef) {
  }

  onClick() {
    this.dcl.loadIntoLocation(ChildComponent, this.elementRef, 'child');
  }
}

Upvotes: 2

Related Questions