Angular2根据服务响应动态选择模板

Angular2 choose template dynamically according to service response

我有一个名为“节点”的组件,它应该显示单个 post,但我有多个 post 类型,并且每种类型都有自己的视图(布局)。

因此该组件有一个 ID 参数,用于从服务获取 post 响应,然后根据 post 类型显示正确的布局。

例如:localhost/test_app/node/123 其中 123 是 id 参数。

方法 1:在模板中使用 ngIf

@Component({
  selector: 'node',
  directives: [Post, Project],
  template: `
    <post *ngIf="response.post.post_type == 'post'" content="response.post"></post>
    <project *ngIf="response.post.post_type == 'project'" content="response.post"></project>
  `,
})

export class Node{

  id: number;
  response: any;
  constructor(private _param: RouteParams,
              public service: Service
  ){
    this.id = +_param.get('id');
  }

  ngOnInit(){
    this.service.get(this.id).subscribe(
      res=> this.response = res.json()
    );
  }

}

方法二:使用动态组件加载器。

@Component({
  selector: 'node',
  directives: [Post, Project],
  template: '<div #container></div>'
})

export class Node{

  id: number;
  response: any;

  constructor(private _param: RouteParams,
              public service: Service,
              private loader:DynamicComponentLoader,
              private elementRef:ElementRef
  ){
    this.id = +_param.get('id');
  }

  ngOnInit(){
    this.service.get(this.id).subscribe(
      res=> {
          this.response = res.json();
          this.renderTemplate();
      }
    );
  }

  renderTemplate(template) {
    this.loader.loadIntoLocation(
      this.getCorrectTemplate(),
      this.elementRef,
      'container'
    )
  }

  getCorrectTemplate(){
    if(this.response.post.post_type == "post"){
        return '<post content="response.post"></post>';
    }
    else{
        return '<project content="response.post"></project>';
    }
  }

}

我想知道哪种方法更有效,或者如果有更好的方法,请分享。

如果您的可用模板集有限,那么 *ngIf*ngSwitch 是一个不错的方法。它允许您在父子之间使用 []() 绑定。

如果您有一组静态未知的模板,例如由参数提供的模板,则 *ngIf 不起作用。那么ViewContainerRef.createComponent()(代替DynamicComponentLoader)才是正确的做法。有关示例,请参见