簡體   English   中英

Angular 2 transclusion,指令內容為“alt”

[英]Angular 2 transclusion, directive content into “alt”

我在這里有一個簡單的問題,但找不到解決方案...所以這是我的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;
}

如果你仍然想要使用transclude,你可以使用<ng-content> ,從DOM讀取被轉換的內容並將它分配給你綁定的屬性<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;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM