我这里有一个简单的问题,但找不到解决方案... 所以这是我的 logo.components.ts :
import {Component} from '../../../../frameworks/core/index';
@Component({
moduleId: module.id,
selector: 'my-logo',
templateUrl: 'logo.component.html',
styleUrls: ['logo.component.css']
})
export class LogoComponent {}
所以我将它导入到我的 home.component.ts 中:
import {LogoComponent} from '../../frameworks/mysite/components/logo/logo.component';
<my-logo>AltText</my-logo>
所以我的模板 logo.component.html 看起来像这样:
<div class="logo-icon">
<img alt="" src="../../images/logo-icon.svg" />
</div>
所以我想要我的
<my-logo>AltText... or any content text from here.... </my-logo>
指令内容插入到我的 logo.component.html 中,
<img alt="INSERTED HERE" src="../../images/logo-icon.svg" />
.
我知道
<ng-content></ng-content>
但在这种情况下,我不知道插入“alt”的正确方法... 预先感谢您的帮助!
最佳答案
您不能嵌入到属性中,只能嵌入到元素子元素中。
您可以将值作为属性传递
<my-logo alt="AltText"></my-logo>
在你的组件中
@Component({
template: `
<div class="logo-icon">
<img [alt]="alt" src="../../images/logo-icon.svg" />
</div>
`
})
export class MyLogo {
@Input() alt:string;
}
如果您仍想使用转包,您可以使用 <ng-content>
转包它, 从 DOM 中读取嵌入的内容并将其分配给您绑定(bind)的属性 <img [alt]="...">
但这很麻烦。
更新 - 使用嵌入
<div class="logo-icon">
<div #wrapper hidden="true"><ng-content></ng-content><div>
<img [alt]="alt" src="../../images/logo-icon.svg" />
</div>
获取嵌入的内容
export class LogoComponent {
@ViewChild('wrapper') content:ElementRef;
ngAfterViewInitInit():any {
this.alt = this.content.nativeElement.innerHTML;
}
}
关于javascript - Angular 2 包含,指令内容到 "alt",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39071578/