Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

angular - How can I have dynamic templateUrl for Angular2 Component?

I wanted to load component templateUrl based on value passed from parent component. I know tt can be pass through property binding to component by have @Input, I gave example below in which myHtml will be passed as templateName.

.But there is no ability to access @Input value inside templateUrl function. I think templateUrl is the first thing going to evaluate by asking for HTML, after that all other component code gets executed.

Like in angular 1 has ability to pass some value from attribute, & then I can use that value inside templateUrl function as a parameter like below.

templateUrl: function(element, attrs){
    //was getting value
    return '/app/templates/'+ attrs.myTemplateName + '.html'
}

But same thing I can't do in Angular2, as templateUrl is strongly typed as string so it doesn't take function as an attribute.

Is there a way to achieve this OR I missed something simple?

Edit

I've already looked at this answer which isn't what I want. In referred answer, it render DOM using DynamicComponentLoader which loads another component.

This is not what I wanted, because creating new separate component for having different templateUrl doesn't make sense in mine case.

Any idea how do I implement this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Been struggling with something similar, but unfortunately you can't do this. Component templates are compiled at runtime. So, basically, I would make a component that compiles other child components (which I actually did)

DynamicComponentLoader is beign deprecated. You need to use the ComponentResolver class to load other components inside the main one, like so:

function makeComponent( selector, template, ...more )
{
  @Component({ selector: selector, template: template })
  class FakeComponent {}
  return FakeComponent;
}

@Component({ ... })
export class MainCmp implements OnInit
{
  // place to insert
  @ViewChild('viewChild', {read: ViewContainerRef}) viewChild: ViewContainerRef;

  constructor(private compiler: ComponentResolver){}
  // or OnChanges, or event binding.. should work

  ngOnInit()
  {
    // decide on your custom logic here, get you @Input, whatever...

    // and you can actually make some custom dynamic component...
    let childCmp = makeComponent( custom, stuff, here );

    // compile then insert in your location, defined by viewChild
    this.compiler.resolveComponent( childCmp )
      .then( (compFactory:ComponentFactory) => this.viewChild.createComponent(compFactory) )
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...