Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 + Semantic UI , component encapsulation breaks style

I'm using Angular2 with Semantic UI as a css library. I have this piece of code:

<div class="ui three stakable cards">
   <a class="ui card"> ... </a>
   <a class="ui card"> ... </a>
   <a class="ui card"> ... </a>
</div>

the cards are rendered nicely with a space between and such. like this: refer to cards section in the link

since the cards represent some kind of view I thought of making a component out of it, so now the code is:

<div class="ui three stakable cards">
   <my-card-component></my-card-component>
   <my-card-component></my-card-component>
   <my-card-component></my-card-component>
</div>

but now the style is broken, there is no space between them anymore.

Is there any nice way of fixing this ?


the first thing I thought of doing is this:

my-card-component OLD template:
<a class="ui card">
    [some junk]
</a>

           |||
           VVV

my-card-component NEW template:
[some junk]

and instantiating like:
<my-card-component class="ui card"></my-card-component>
or like:
<a href="?" my-card-component></a>

but this is not satisfactory since I want to be able to pass in an object and the component would automatically set the [href]=obj.link.


in AngularJS 1.0 there was a replace: true property which does excatly what i need, is there a similar thing in Angular2 ?

like image 897
user47376 Avatar asked Jan 10 '16 15:01

user47376


2 Answers

There is no replace=true in Angular2. It is considered a bad solution and deprecated in Angular 1.x as well.
See also Why is replace deprecated in AngularJS?

Use an attribute-selector instead of a tag-selector in your component or directive.

Just change

@Directive({ ..., selector: "my-card-component"})

to

@Directive({ ..., selector: "a[my-card-component]"})

and use it like

<a my-card-component class="ui card"> ... </a>

You might also adjust the encapsulation strategy http://blog.thoughtram.io/angular/2015/06/29/shadow-dom-strategies-in-angular2.html but I think the default emulated should be fine in your case.

like image 121
Günter Zöchbauer Avatar answered Nov 18 '22 15:11

Günter Zöchbauer


Solved it using @GünterZöchbauer Answer together with @HostBinding('href') so now the code is:

template:
---------
[some junk]

component:
----------
@Component({
    selector: 'a[my-card-component].ui.card',
    templateUrl: 'urlOfSomeJunk.html',
    directives: []
})
export class ProblemCardComponent {
    @Input()
    obj: MyObject;

    @HostBinding('attr.href') get link { return this.obj.link; }
}

instantiating:
--------------
<a class="ui card" my-card-component [obj]="someBindingHere"></a>

that way the href is automatically bound to obj.link and I can rest in piece.

like image 29
user47376 Avatar answered Nov 18 '22 13:11

user47376