【问题标题】:Is there any way to modify the projected content using ng-content in Angular?有没有办法在 Angular 中使用 ng-content 修改投影内容?
【发布时间】:2022-01-11 10:48:08
【问题描述】:

我有两个组件。我们称它们为 hostComponent 和 textComponent。我想在textContent里面投影一些内容,需要根据其他一些输入属性修改投影出来的内容。

<app-text-component characterCount='5'>
    <span> Hello World </span>
</app-text-component>

在上面的示例代码中,该组件应显示“Hello”,因为传递给该组件的字符计数输入值为 5。

如何将投影的内容裁剪为仅n个字符并显示相同,其中n是characterCount输入属性的值?

【问题讨论】:

  • 有两种可能的方式。要么构建一个管道来处理它,要么在组件内部对 Input-Event 使用插值反应。后者意味着通过插值显示您的文本并缩短变量内容的长度。

标签: angular angular-content-projection


【解决方案1】:

您可以在构造函数中使用renderer:Renderer2el: ElementRef 并修改&lt;ng-content&gt;&lt;/ng-content&gt; 的值:

this.span = this.renderer.createElement('span');
this.span.innerHTML = `<div>Hello</div>`;
this.renderer.appendChild(this.el.nativeElement.parentElement, this.span);
// this.renderer.removeChild(parent, child);

您可以像这样删除元素或修改 textComponent 中的元素。

【讨论】:

    【解决方案2】:

    您应该使用对象变量在两个组件之间共享信息。这样,您可以修改任何组件中的任何属性对象,并且可以观察到两个组件中反映的更改。如果使用简单变量,则不能使用双向数据绑定。 说了……你可以的:

    父组件:

    configObject = { count: 5, text: 'hello world' }.
    

    模板

    <app-text-component config-object='configObject'></app-text-component> 
    

    子组件

    然后...在您的子组件中,您可以使用函数返回修剪文本:

    @Input() configObject: object;
    
    trimText() {
      return this.configObject.text.substring(0, this.configObject.count);
    }
    

    模板

    <span>{{ trimText() }}</span>
    

    【讨论】:

      猜你喜欢
      • 2019-08-24
      • 2021-10-14
      • 2017-07-13
      • 2016-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-19
      • 2019-09-29
      相关资源
      最近更新 更多