Angular 2自定义模板CSS问题+事件绑定

时间:2017-01-17 13:33:41

标签: angular angular2-template

由于我必须在自定义模板中绑定click事件,因此我遇到了CSS问题。所以我有一个组件,基本上输出一个列表与项目'模板在"父组件"。

中定义

具有自定义模板的可重用列表组件

@Component({
    selector: 'my-list',
    template: `
        <span *ngFor="let item of items" (click)="pickItem(item)">
            <template
                ngFor let-number [ngForOf]="[card]"
                [ngForTemplate]="itemTmpl"
            ></template>
        </span>
    `
})

export class MyListComponent {
    @Input() items: Item[];
    @ContentChild(TemplateRef) itemTmpl: TemplateRef<ElementRef>;
    @Output() onItemPick = new EventEmitter<Item>();

    pickItem(item: Item) {
        item.picked = !item.picked;
        if (item.picked) {
            console.log('Item was picked!')
        } else {
            console.log('Item was unpicked!');
        }

        this.onItemPick.emit(item);
    }
}

使用列表组件

@Component({
    selector: 'shopping-list',
    template: `
        <my-list [items]="itemsList">
            <template let-temp>
                <span [class.picked]="temp.picked">
                    {{ temp.name }}
                </span>
            </template>
        </my-list>
    `
})

export class ShoppingListComponent {
    itemsList: Item[] = [
        new Item('Apples'),
        new Item('Bananas'),
        new Item('Carrots')
    ];
}

正如您在my-list组件中看到的那样,我包装了span收到的模板。我这样做的唯一原因是允许我将pickItem()点击事件绑定到模板。

CSS问题

以上组件产生以下HTML:

<shopping-list>
    <my-list>
        <span>
            <span class="picked">
                Apples
            </span>
        </span>
        <span>
            <span>
                Bananas
            </span>
        </span>
        <span>
            <span>
                Carrots
            </span>
        </span>
    </my-list>
</shopping-list>

shopping-list组件CSS中,我有margin-bottom: 10px列表项,但是我希望last-child拥有margin-bottom: 0我无法使用last-child或在my-list组件中使用CSS。从我的尝试看来,我似乎无法通过CSS实现这一点,因为我有一个&#34;包装&#34;跨越模板。

我认为理想的解决方案是自定义模板不会使用&#34;包装器生成#34;元素,但在这种情况下,我不确定如何绑定click事件。有没有办法以不同的方式解决这个问题?

更新

这是关于我所遇到的问题的一个例子:https://plnkr.co/edit/djq2fWYkw4EhjYhD24nb

1 个答案:

答案 0 :(得分:1)

您应该能够使用现有的html以及直接后代和last-child css选择器来实现所需的结果。

CSS

my-list > span:not(:last-child) {
    margin-bottom: 10px;
}

SNIPPIT

my-list > span:not(:last-child) {
  margin-bottom: 10px;
}
span.picked {
  background: #9999FF;
}
my-list > span {
  display: block;
}
shopping-list {
  background: #55FF55;
  display: block;
}
<shopping-list>
  <my-list>
    <span>
            <span class="picked">
                Apples
            </span>
    </span>
    <span>
            <span>
                Bananas
            </span>
    </span>
    <span>
            <span>
                Carrots
            </span>
    </span>
  </my-list>
</shopping-list>

编辑1

您可以更新全局样式以获得所需的结果。如果您只想修改组件的css,我建议使用shadow-dom穿孔opperater,>>>/deep/。第三种选择是将输入参数传递给组件,指示它是最后一个子项,然后使用ngClass指令应用条件样式。

使用全局样式

my-list > span:last-child > span{
    margin-bottom: 0;
}

Plunker