4

I have a simple question here, and yet can't find a solution... So here is my 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  {}

So i'm importing it in my home.component.ts :

import {LogoComponent} from '../../frameworks/mysite/components/logo/logo.component';

<my-logo>AltText</my-logo>

So my template logo.component.html looks like this:

<div class="logo-icon">
  <img alt="" src="../../images/logo-icon.svg" />
</div>

So i would like my

<my-logo>AltText... or any content text from here.... </my-logo>

directive content inserted into my logo.component.html , <img alt="INSERTED HERE" src="../../images/logo-icon.svg" />.

I know about the

<ng-content></ng-content>

But in this case i don't know the proper way to insert in into "alt"... Thanks in advance for your help!

1 Answers1

2

You can't transclude into an attribute, only to elements children.

You can pass the value as attribute

<my-logo alt="AltText"></my-logo>

In your component

@Component({
  template: `
<div class="logo-icon">
  <img [alt]="alt" src="../../images/logo-icon.svg" />
</div>
`
})
export class MyLogo {
  @Input() alt:string;
}

If you still want to use transclude, you can transclude it using <ng-content>, the read the transcluded content from the DOM and assign it to a property you bind <img [alt]="..."> to but that's quite cumbersome.

Update - using transclusion

<div class="logo-icon">
  <div #wrapper hidden="true"><ng-content></ng-content><div>
  <img [alt]="alt" src="../../images/logo-icon.svg" />
</div>

get the transcluded content

export class LogoComponent  {
  @ViewChild('wrapper') content:ElementRef; 

  ngAfterViewInitInit():any {
    this.alt = this.content.nativeElement.innerHTML;
  }
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thanks for the answer! But i would still like to know if there is to get text from the inside the directive `AltText` and stick it into alt, with no adding `alt="..."` into `` I've recently started working with angular framework, so maybe asking pretty dumb question, coz of lack of experience .... – Matvey Nevazhno Aug 22 '16 at 05:43
  • 1
    I updated my answer. See also http://stackoverflow.com/a/37586026/217408 – Günter Zöchbauer Aug 22 '16 at 05:48
  • `@Input() alt:string;` - worked fine actually `@ViewChild('wrapper') content:ElementRef;` - this approach did not work though, i double checked everything and yet it says alt = 'undefined'. – Matvey Nevazhno Aug 27 '16 at 16:49
  • 1
    You can't access `@ViewChild()` results in the constructor, only in or after `ngAfterViewInit()`. If input works for you it's fine of course as well. – Günter Zöchbauer Aug 27 '16 at 18:36