Home > OS >  Is there any way to modify the projected content using ng-content in Angular?
Is there any way to modify the projected content using ng-content in Angular?

Time:12-06

I have two components. Let's call them hostComponent and textComponent. I want to project some content inside textContent, and need to modify the projected content according to some other input properties.

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

In this example code above, this component should display 'Hello', as the character count input passed to this component has the value 5.

How to trim the projected content to only n characters and display the same, where n is the value of characterCount input property?

CodePudding user response:

You can use renderer:Renderer2 and el: ElementRef in your constructor and modify <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);

you can remove element or modify element in your textComponent like this.

CodePudding user response:

You should use an object variable to share info between both components. This way you can modify any property object in any component and you can watch the change reflected in both components. If you use a simple variable you cannot use two way data binding. Said that... you can do it:

Parent component:

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

Template

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

Child component

Then... In your child component you can use a function to return trim text:

@Input() configObject: object;

trimText() {
  return this.configObject.text.substring(0, this.configObject.count);
}

Template

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