1

i have been writing an application in angular and i am getting to grips with most stuff pretty well. One thing i don't understand is structural directives or anything that uses code changes the DOM

For the simplest example of what I'm looking to learn, in a parent template if i have

<div [addTitle]='sometitle'>
   <child-component></child-component>
</div>

i want to build a directive that when i add a div with [addTitle]='sometitle' attribute it alters the final code to this

<div [addTitle]='sometitle'>
   <h2>sometitle</h2>
   <child-component></child-component>
</div>

whilst keeping the content of <child-component></child-component> unaltered and with all the bindings within intact etc.

i know i need a file such as

import { Directive, Input } from '@angular/core';

@Directive({
  selector: '[addTitle]'
})
export class addTitleDirective {
  constructor() { }
}

i just don't known how to access the inner 'html' of the tag with the directive on it or keep the child-component from being destroyed or how to add the <h2>sometitle</h2> to the DOM or show the html that is inside the <child-component> back to the DOM

im sorry if this is to general but i am looking for some pointers to help me get started.

edit inorganik has kindly pointed out that a component is more suited and given example ..thank you.

i was wondering if i had

<div [addTitles]="['sometitle1', 'sometitle2']">
   <child-component1></child-component1>
   <child-component2></child-component2>
</div>

and wanted to end up with

<div [addTitle]="['sometitle1', 'sometitle2']">

   <h2>sometitle1</h2>
   <child-component1></child-component1>

   <h2>sometitle2</h2>
   <child-component2></child-component2>

</div>

would a component still work?

1 Answer 1

2

I believe you are looking for ng-content. Also I think your example would be better served by a component than directive - So your component might look like this:

@Component({
  selector: 'app-title',
  templateUrl: './title.component.html',
  styleUrls: ['./title.component.scss'],
})
export class TitleComponent {

  @Input() addTitle: string;

}

template:

<h2>{{ addTitle }}</h2>
<ng-content></ng-content>

Then you use it like this:

<app-title [addTitle]="'my title'">
  <child-component></childcomponent>
</app-title>
Sign up to request clarification or add additional context in comments.

1 Comment

I would also mention that we can use attribute selector [addTitle] for component just to not introduce a new element

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.