3

I just started to convert my Angular 1.x directives to Angular 2 components but I stuck in the first place. I have 2 directives namely row-field and column-field. They can be used to create bootstrap 12 unit grid like so;

<row-field>
    <column-field span="4">First Cell</column-field>
    <column-field span="2" offset="1">Second Cell</column-field>
    <column-field span="4">Third Cell</column-field>
</row-field>

This will output a html like below;

<div class="row">
    <div class="span4">First Cell</div>
    <div class="span2 offset1">Second Cell</div>
    <div class="span4">Third Cell</div>
</div>

It is fairly easy in Angular 1.x using tranclude and replace properties of directive. But I am having trouble about creating the same behaviour in Angular 2. My column-field component is like this;

@Component({
    selector: 'column-field',
    template: '<ng-content [ngClass]="'span{{span}} offset{{offset}}'"></ng-content>',
    directives: [NgClass]
})
export class ColumnFieldComponent {
    @Input() span;
    @Input() offset;
}

But it is not creating the desired html output. There is always a column-field tag in the output, what I want is to replace column-field tag with a div tag and move its attributes to this new div tag.

Any advice will be appreciated.

ibrahimb
  • 170
  • 1
  • 10
  • Using an attribute selector for your component (instead of a tag selector) will let you get rid of the `column-field` tag. See Günter's answer here: http://stackoverflow.com/a/38716164/533454 – Greg Aug 02 '16 at 09:21

1 Answers1

5

Angular2 doesn't support such a kind of replace.

You also can't add classes or other attributes (except select="...") like [ngClass]="'span{{span}} offset{{offset}}'". This won't have any effect because the <ng-content> element is never being added to the DOM. It's just creates an internal marker where to transclude child elements to.

You can wrap <ng-content> like

template: `
<div [ngClass]="'span{{span}} offset{{offset}}'">
  <ng-content></ng-content>
</div>
`,
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567