TemplateRef内容到变量

JoG*_*JoG 1 typescript transclusion angular

我想以ng-content简单的字符串形式获取组件的innerText 以便能够重用它。

我尝试过这样的事情:

@Component({
  selector: 'my-comp',
  template: `
    <div class="text-container">
      <span class="text" [title]="text">{{text}}</span>
    </div>
    <ng-template #text>
      <ng-content></ng-content>
    </ng-template>
  `
})
export class MyComponent implements AfterViewInit {
  @ViewChild('text') text: TemplateRef<string>;

  ngAfterViewInit(): void {
    console.log(this.text);
  }
}
Run Code Online (Sandbox Code Playgroud)

我这样使用它:

<my-com>
  My simple string text
</my-com>
Run Code Online (Sandbox Code Playgroud)

目的是让我的字符串My simple string text进入变量text...

有什么想法吗?

Gün*_*uer 6

我不认为您想要的东西可以解决(请参阅问题下方的评论)

我的建议是

<ng-template #text>My simple string text</ng-template>
<my-comp [text]="text"></my-comp>
Run Code Online (Sandbox Code Playgroud)

并得到像

  @Input() text: TemplateRef<string>;

  ngAfterViewInit(): void {
    console.log('text', this.text);
  }
Run Code Online (Sandbox Code Playgroud)

然后您可以使用模板引用来输出它

<ng-container *ngTemplateOutlet="text"></ng-container>
Run Code Online (Sandbox Code Playgroud)

StackBlitz示例


JoG*_*JoG -3

最后我找到了与我想做的事情相对应的解决方案:

堆栈闪电战样本

应用程序组件.ts

@Component({
  selector: 'my-app',
  template: `
    <div>
      <text-ellipsis>My very very very very long text sentence</text-ellipsis>
    </div>
  `,
  styles: [`
    div {
      width:100px
    }
  `]
})
export class AppComponent  {
}
Run Code Online (Sandbox Code Playgroud)

文本省略号.component.ts

@Component({
  selector: 'text-ellipsis',
  template: `
    <div class="text-container">
      <span [title]="text.innerText" #text><ng-content></ng-content></span>
    </div>
  `,
  styles: [`
    .text-container {
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }
  `]
})
export class TextEllipsisComponent {
}
Run Code Online (Sandbox Code Playgroud)

ng-content通过这种方式,我可以显示并在属性中设置它提供的文本title