【问题标题】:angular2 nested componentsangular2 嵌套组件
【发布时间】:2016-03-01 01:34:21
【问题描述】:

我有多个组件,每个组件都有自己的视图模板(angular2 alpha 46)

  • PostCmp
  • CommentCmp
  • ShareCmp

我想从一个主组件加载它们并在它自己的视图模板中显示它们

  • SingleCmp

我将首先通过“SingleCmp”加载一个组件“PostCmp”

PostCmp:

import { Component, Injectable, CORE_DIRECTIVES } from 'angular2/angular2';
import { HTTP_PROVIDERS } from 'angular2/http';
import { ROUTER_DIRECTIVES, RouteParams } from 'angular2/router';
import { WPService } from './../../lib/wpservice';
import { Post } from './../../lib/PostType';

@Component({
	selector: 'post',
	viewProviders: [HTTP_PROVIDERS, WPService],
	templateUrl: './app/shared/post/post.html',
	directives: [CORE_DIRECTIVES]
})
export class PostCmp {
	post: Post;
	constructor(id: string, service: WPService) {
		//this.post = new Post(params.get('id'), service); original
      this.post = new Post(id, service);
	}
}
<h1 [inner-html]="post.title"></h1>
<div *ng-if="post.featured_image_url!==''" class="post-thumbnail">
	<img width="250" height="auto" [src]="post.featured_image_url" />
</div>
<div class="post-date">
	{{post.date}}
</div>
<div class="post-content" [inner-html]="post.content"></div>
</div>

上面的组件已经过测试并且可以正常工作了。

SingleCmp:

import { Component, Injectable, CORE_DIRECTIVES } from 'angular2/angular2';
import { HTTP_PROVIDERS } from 'angular2/http';
import { ROUTER_DIRECTIVES, RouteParams } from 'angular2/router';
import { WPService } from './../../lib/wpservice';


import { PostCmp } from './../../shared/post/post';

@Component({
	selector: 'single',
	viewProviders: [HTTP_PROVIDERS, WPService, PostCmp],
	templateUrl: './app/components/single/single.html',
  	directives: [ROUTER_DIRECTIVES]
})
export class SingleCmp {
    //how can I display PostCmp from SingleCmp template??
	post: PostCmp;
	constructor(params: RouteParams, service: WPService) {
		post = new PostCmp(params.get('id'), service);
	}
}
<!-- something like this -->
{{post}}

<!--{{share}}-->
<!--{{comment}}-->

我怎样才能做到这一点?

【问题讨论】:

    标签: typescript components angular


    【解决方案1】:

    你的 SinglCmp 应该是这样的

    <SinglCmp>
      <PostCmp></PostCmp>
      <ShareCmp></ShareCmp>
      <CommentCmp></CommentCmp>
    </SinglCmp>
    

    确保在您的 SinglCmp 组件中正确导入组件并添加指令。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      • 2017-03-25
      • 1970-01-01
      • 2017-07-29
      • 1970-01-01
      • 2017-09-21
      • 1970-01-01
      相关资源
      最近更新 更多