在<ng-content></ng-content>内动态添加span标签链接

Dynamically add span tag to link inside <ng-content></ng-content>

本文关键字:ng-content span 标签 链接 添加 动态      更新时间:2023-09-26

我有一个自定义列表项组件,以<ng-content>为模板:

import { Component, Input } from '@angular/core';
@Component({
    selector: '[my-list-item]',
    template: '<ng-content></ng-content>'
})
export class MyListItemComponent {
    @Input() active = false; 
}

用户可以设置激活状态。

<ul>
    <li my-list-item [active]="true">
        <a href="#">Stackoverflow</a>
    </li>
</ul>

如果active标志被设置为true,我必须在链接中添加一个自定义span标签,它应该像这样呈现:

<ul>
    <li>
        <a href="#">
            <span class="active">Stackoverflow</span>
        </a>
    </li>
</ul>

在angular2中推荐的方法是什么?谢谢你的建议

我会利用以下方法:

@Directive({ selector: 'li>a' })
export class MyAnchorDirective {
  constructor(private elRef: ElementRef, private rendered: Renderer) { }
  public wrapContent() {
    var el = this.elRef.nativeElement;
    this.rendered.setElementProperty(el, 'innerHTML', 
       `<span class="active">${el.innerHTML}</span>`);
  }
}
@Component({
  selector: '[my-list-item]',
  template: '<ng-content></ng-content>'
})
export class MyListItemComponent {
  @Input() active = false;
  @ContentChild(MyAnchorDirective) anchor: MyAnchorDirective;
  ngAfterContentInit() {
    if (this.active && this.anchor) {
      this.anchor.wrapContent();
    }
  }
}
@Component({
  selector: 'my-app',
  template: `
    <ul>
      <li my-list-item [active]="true">
          <a href="#">Stackoverflow</a>
      </li>
      <li my-list-item [active]="false">
          <a href="#">Stackoverflow2</a>
      </li>
    </ul>`
})
export class AppComponent { }
<<p> 恰好例子/strong>

在内部设置div,然后设置任何div内容

<ul>
  <li my-list-item [active]="true">
    <a href="#"><div id='you_can_do_it_in_a_div'>Stackoverflow</div></a>
  </li>
</ul>
<script>
document.getElementById('you_can_do_it_in_a_div').innerHTML = 'whatever';
</script>

未测试

你的占位符应该像

<ng-content *ngIf="active"></ng-content>

在主HTML文件

将组件修改为

    import Component from '@angular/core';
    @Component({
        selector: '[my-list-item]',
        template: `
               <ul>
                   <li>
                       <a href="#">
                           <span class="active">Stackoverflow</span>
                       </a>
                  </li>
             </ul>
        `
    })
    export class MyListItemComponent {
        active = false; 
    }

要注意模板语法,它是反勾号(')-它与单引号(')不同-允许您将字符串组成几行,这使HTML更具可读性。

为什么要导入Input ?