在<ng-content></ng-content>内动态添加span标签链接
Dynamically add span tag to link inside <ng-content></ng-content>
我有一个自定义列表项组件,以<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 ?
相关文章:
- 使用Clipboard.js复制span文本
- ng映射方向备选方案
- AngularJS UI路由器不能像ng路由器那样工作
- 角度:在ng重复上切换图像
- 正在使用$location.path(.)路由ng视图
- AngularJS:ng之后,重复$scope值未按预期更新
- ng打开空字符串
- 我应该使用Ng提交还是点击表格
- ng init中的表达式无法使用ng repeat
- ng更改事件不适用于Dropdown
- ng视图外的链接重定向到ng视图内的页面
- ng应用程序使脚本无限运行
- ng-include is not including content.html
- Angularjs动态ng-if数据绑定在span中
- ng disabled不适用于span标记
- 循环HTML变量并将span替换为content
- 用ng-model动态禁用一个span
- angularjs中的Ng-show不支持span
- Angular 2根组件中的ng-content
- TimelineJs and AngularJs ng-view content