Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 access ng-content within component

How can I access the "content" of a component from within the component class itself?

I would like to do something like this:

<upper>my text to transform to upper case</upper> 

How can I get the content or the upper tag within my component like I would use @Input for attributes?

@Component({     selector: 'upper',     template: `<ng-content></ng-content>` }) export class UpperComponent {     @Input      content: String; } 

PS: I know I could use pipes for the upper case transformation, this is only an example, I don't want to create an upper component, just know how to access the component's content from with the component class.

like image 449
Daniel Kobler Avatar asked Apr 11 '16 10:04

Daniel Kobler


People also ask

How do I access Ng-content?

Once you project content into App Component using ng-content. Now, using the template reference variable “#contentParagraph” you can access ng-content using @ContentChild within Angular component (ItemElementComponent) class as shown below.

What is Contentprojection in Angular?

Content projection is a pattern in which you insert, or project, the content you want to use inside another component. For example, you could have a Card component that accepts content provided by another component.


1 Answers

If you want to get a reference to a component of the transcluded content, you can use:

@Component({     selector: 'upper',     template: `<ng-content></ng-content>` }) export class UpperComponent {     @ContentChild(SomeComponent) content: SomeComponent; } 

If you wrap <ng-content> then you can access access to the transcluded content like

@Component({     selector: 'upper',     template: `   <div #contentWrapper>     <ng-content></ng-content>   </div>` }) export class UpperComponent {     @ViewChild('contentWrapper') content: ElementRef;      ngAfterViewInit() {       console.debug(this.content.nativeElement);     } } 
like image 103
Günter Zöchbauer Avatar answered Sep 29 '22 11:09

Günter Zöchbauer