transclude and Require on Angular4

Viewed 52

I'm trying to convert this component of angularJs 1.6 to angular 4 and I can't find the solution for require and transclude:

Here AngularJs version:

const partnerTabComponent = {
  selector: 'ypUiPartnerTab',
  controller : PartnerTabController,
  template,
  transclude: true,
  require: {
    parent: '^ypUiPartnerTabs'
  },
  bindings: {
    label: '<'
  }
}

And here Angular version:

@Component({
  selector: 'yp-ui-partner-tab',
  templateUrl: './partner-tab.component.html',
  styleUrls: ['./partner-tab.component.less']
})
export class PartnerTabComponent implements OnInit {

  @Input() label: any

  constructor() { }
}

I want to add transclude element and require, in this Angular version.

It maybe very easy, but I can't find the solution right now.

1 Answers

There is no require in angular, you can however inject the parent component into your child component. If the child component is not inside the parent, your application will throw an error:

@Component({...})
export class PartnerTabComponent implements OnInit {

  constructor(private readonly partnerTabs: PartnerTabsComponent) {}

}

For the transclude bit, I believe you can use the ng-content tag:

If you have a parent component template like this:

<yp-ui-partner-tab>
  <div>this is sparta!</div>
</yp-ui-partner-tab>

You can render your 'sparta' inside your partner-tab at the position where you place your ng-content tag:

@Component({
  selector: 'yp-ui-partner-tab',
  template: `
      <div>What is this?</div>
      <ng-content></ng-content>
  `
})
export class PartnerTabComponent implements OnInit {

  constructor(private readonly partnerTabs: PartnerTabsComponent) {}

}
Related