Nitesh
Nitesh

Reputation: 1550

Pass external component as property in Angular2+

Suppose there is a component ButtonComponent and SideComponent. How to pass 'ButtonComponent' as a property to 'SideComponent'?

For eg,

@Component({
  selector: 'my-btn',
  template: '<span>My button</span>'
})
export class ButtonComponent implements OnInit {

} 


@Component({
  selector: 'my-side',
  template: '<div><div class="btn-section">{{myBtn}}</div><div class="content-section"><ng-content></ng-content></div></div>'
})
export class SideComponent implements OnInit {
   @Input() myBtn:any = null;
}

Usage:
<my-side [myBtn]="btnTmpl">
  Hello, this is my content
</my-side>
<my-btn #btnTmpl></my-btn> 

But this doesn't work, final template shows [Object Object] as output.

Upvotes: 0

Views: 1903

Answers (2)

Chellappan வ
Chellappan வ

Reputation: 27409

Use ng-template

app.component.html

<my-side>
  <ng-template>
      <my-btn></my-btn> 
  </ng-template>
</my-side>

ts

  @ContentChild(TemplateRef) template:TemplateRef<any>;
  constructor() { }
  ngAfterViewInit() {
    console.log(this.template);
  }

Example:https://stackblitz.com/edit/child-parent

Upvotes: 0

Todd Palmer
Todd Palmer

Reputation: 1102

One way to do this is to use ng-content. ng-content is a way to display dynamic HTML in your component.

Todd Motto has a good writeup here: https://toddmotto.com/transclusion-in-angular-2-with-ng-content

So your code would look something like this:

@Component({
  selector: 'my-btn',
  template: '<span>My button</span>'
})
export class ButtonComponent implements OnInit {

} 


@Component({
  selector: 'my-side',
  template: '<div><ng-content></ng-content></div>'
})
export class SideComponent implements OnInit {
}

Usage then looks like this:

<my-side>
  <my-btn></my-btn>
</my-side>

Upvotes: 5

Related Questions