相关疑难解决方法(0)

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

我有一个名为"Node"的组件,它应该显示一个帖子,但我有一个以上的帖子类型,每个类型都有自己的视图(布局).

所以这个组件有一个ID参数,用于从服务获得post响应,然后根据post类型显示正确的布局.

例如:localhost/test_app/node/123123是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()
    );
  }

}
Run Code Online (Sandbox Code Playgroud)

方法2:使用动态组件加载器.

@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 …
Run Code Online (Sandbox Code Playgroud)

components angular

9
推荐指数
1
解决办法
3435
查看次数

标签 统计

angular ×1

components ×1