How to bind ng-content to property?

I want to bind ng-content to child component property. Is it possible?
For example for <myComponent>123</myComponent> MyComponent.content should be set to 123.

@Directive({
  selector: 'myComponent'
})
class MyComponent {
  content;          // should be set to 123
}

@Component({
  selector: 'app',
  directives: [MyComponent],
  template: `
    <myComponent>123</myComponent>
  `
})
export class App { }

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest
@Directive({
  selector: 'myComponent'
})
class MyComponent {
  content;          // should be set to 123

  constructor(private elementRef:ElementRef) {
    this.content = this.elementRef.nativeElement.innerHTML;
  }

  // to ensure bindings have been resolved
  // see also 
  // https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#aftercontent
  afterContentChecked() {
    this.content = this.elementRef.nativeElement.innerHTML;
  }
}

Plunker example

Jason
Guest

If you need binding – i.e., the value 123 can change – and you want the directive to pick up any changes, implement lifecycle hook ngAfterContentChecked(): @Directive({selector: 'myComponent'}) export class MyComponent { content:string; constructor(private _elRef: ElementRef) {} ngAfterContentChecked() { this.content = this._elRef.nativeElement.textContent; // or maybe innerHTML, depending on what you want console.log('new value:', this.content); } } @Component({ selector: 'my-app', template: `<myComponent>{{number}}</myComponent> <button (click)="number = number + 1">increment</button> <button (click)="0">do nothing event</button> <br>look at console log for directive binding updates`, directives: [MyComponent] }) export class AppComponent { number = 123; constructor() { console.clear(); } } Plunker Note that ngAfterContentChecked() is called… Read more »