加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2 – 将条件样式应用于指令的子HTML元素

发布时间:2020-12-17 10:33:47 所属栏目:安全 来源:网络整理
导读:我正在尝试基于click事件将类应用于 HTML元素.从父组件的模板设置子组件的选择器的类属性时,这可以正常工作,如下面的父组件片段所示: [class.bordered]='isSelected(item)' 这将适当地设置单击该项目时的样式.但是,我想基于相同类型的click事件在子组件中设
我正在尝试基于click事件将类应用于 HTML元素.从父组件的模板设置子组件的选择器的类属性时,这可以正常工作,如下面的父组件片段所示:
[class.bordered]='isSelected(item)'

这将适当地设置单击该项目时的样式.但是,我想基于相同类型的click事件在子组件中设置内部HTML元素的类,这里是子组件样式的所需目标:

template: `
  <div class="This is where I really want to apply the style">  
    {{ item.val }}
  </div>
`

有没有办法做到这一点,很容易支持?或者这被认为是一种不好的做法,我应该设计我的组件以避免这种条件样式的情况?

完整代码:

@Component({
  selector: 'parent-component',directives: [ChildComponent],template: `
    <child-component
      *ngFor='#item of items'
      [item]='item'
      (click)='clicked(item)'
      [class.bordered]='isSelected(item)'>
    </child-component>
  `
})
export class ParentComponent {
  items: Item[];
  currentItem: item;

  constructor(private i: ItemService) {
    this.items = i.items;
  }

  clicked(item: Item): void {
    this.currentItem = item;
  }

  isSelected(item: Items): boolean {
    if (!item || !this.currentItem) {
      return false;
    }
    return item.val === this.currentItem.val;
  }
}


@Component({
  selector: 'child-component',inputs: ['item'],template: `
    <div class="This is where I really want to apply the style">  
      {{ item.val }}
    </div>
  `
})
export class ChildComponent {}
向子组件添加样式
@Component({
  selector: 'child-component',template: `
    <div class="This is where I really want to apply the style">  
      {{ item.val }}
    </div>
  `,styles: [`
    :host(.bordered) > div {
    // if this selector doesn't work use instead
    // child-component.bordered > div {
      border: 3px solid red;
    }
  `],})
export class ChildComponent {}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读