Angular 2 + Semantic UI , component encapsulation breaks style

血红的双手。 提交于 2019-12-05 21:58:37

问题


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 ?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/34707029/angular-2-semantic-ui-component-encapsulation-breaks-style

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!