【问题标题】:TemplateRef Content to VariableTemplateRef 内容到变量
【发布时间】:2018-07-27 03:30:48
【问题描述】:

我想将组件的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);
  }
}

我是这样使用它的:

<my-com>
  My simple string text
</my-com>

目标是将我的字符串My simple string text 放入变量text ...

想法?

【问题讨论】:

  • 上面的例子中是否显示了该文本?您需要在某处标记模板以使内容变为真实(被添加到 DOM)。我怀疑这是否可行。我认为您应该需要一个包含My simple string text 的模板引用,并根据需要随时标记此模板。 &lt;ng-content&gt; 投影仅用于在特定位置显示现有内容,而不是用于传递。
  • 不,没有显示文本,因为我在变量文本中只有 TemplateRef。这是我的观点,我怎样才能获取我的模板的 innerText 。如果我放置一个带有模板出口的 ng-container,它可以工作,但我还需要将我的文本放在 title 属性中
  • 没有innerText,只要没有&lt;ng-content&gt;,只要&lt;ng-template&gt;没有盖章,就没有&lt;ng-content&gt;

标签: angular typescript transclusion


【解决方案1】:

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

Stackblitz sample

app.component.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  {
}

text-ellipsis.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 {
}

这样,我可以显示ng-content提供的文本,并将其设置在title属性中。

【讨论】:

    【解决方案2】:

    我不认为你想要的东西可以工作(见你问题下方的 cmets)

    我的建议是

    <ng-template #text>My simple string text</ng-template>
    <my-comp [text]="text"></my-comp>
    

    得到它喜欢

      @Input() text: TemplateRef<string>;
    
      ngAfterViewInit(): void {
        console.log('text', this.text);
      }
    

    然后就可以使用模板引用来输出了

    <ng-container *ngTemplateOutlet="text"></ng-container>
    

    StackBlitz example

    【讨论】:

    • 但我想显示“我的简单字符串文本”而不​​是模板对象“[object,object]”。它与stackblitz.com/edit/angular-abvfxy?file=app/my.component.ts 完全相同,但在我的示例中,您可以删除输入参数。我认为最简单的方法是将真实的字符串值作为我的组件的输入传递: 但我只是想知道是否有可能使用嵌入来做到这一点...
    • 抱歉,忘记了输出部分。我更新了示例
    猜你喜欢
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    • 2011-05-12
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多