0

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

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

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

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

4

2 回答 2

0

您可以在构造函数中使用renderer:Renderer2andel: ElementRef并修改<ng-content></ng-content>value :

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 中的元素。

于 2021-12-06T07:40:32.367 回答
0

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

父组件:

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>
于 2021-12-06T07:32:27.320 回答