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.

1
  • 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: stackoverflow.com/a/38716164/533454 Commented Aug 2, 2016 at 9:21

1 Answer 1

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>
`,
Sign up to request clarification or add additional context in comments.

2 Comments

I already tried it but the output becomes <div class="row"><column-field><div class="span4">First Cell</div></column-field>... which is useless for me. Should I create directive instead of component to achieve this replace behaviour
I don't know of a workaround to get the replace behavior.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.