简体   繁体   中英

Nested components elements

I'm stuck on a template/component problem and I couldn't find any answer.

I'm trying to move a plain Javascript project to Angular2. In my project, I actually create some elements by inherit from others. Example:

File header.html

<header class="some_class"></header>

File header_base.html inherits from header.html

<header> <!-- This is the header element from the header.html file. -->
  <img class="some_class" src="path/to/my/image">
  ...
</header>

EDIT: To clarify how I actually do, to 'inherits file from another', I use Javascript.

My problem is that I can't find out how to do that in Angular. My question is, is there any way to accomplish something like that or do I need to change my way of 'templating' things ?

Thanks by advance.

Your question is a little confusing. Can you provide more detail about what the end result should be?

It sounds like what you are looking for is shadow dom insertion point where you have a component that you can put content into. Where you have a component called Header that has some markup and styles applied, but then you can use it in different places with different content?

If so, here is how you would do it (Note: this is Typescript but could be done in plain Javascript. Check the Angular docs for examples):

CustomHeader.ts:

@Component({
  selector: 'custom-header',
  template: '<header class="some-class"><ng-content></ng-content></header>'
})
export class CustomHeader {
  //if you need any logic in that component
}

Then in whatever component you need to use this component, you would import it:

app.ts:

import {CustomHeader} from './CustomHeader';
@Component({
     selector: "my-app",
     directives: [CustomHeader],
     template: `<div>
                  <custom-header>
                       <img class="some_class" src="path/to/my/image" />
                  </custom-header>
                </div>`
})

The result is that when you use the component in your html, its content will get wrapped by the contents of the CustomHeader's template. Not sure if that is exactly what your need was though.

EDIT: Here's a good article describing this type of component: http://blog.thoughtram.io/angular/2015/03/27/building-a-zippy-component-in-angular-2.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM