加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – ng用于重复组件

发布时间:2020-12-17 07:31:58 所属栏目:安全 来源:网络整理
导读:我有两个组件,一个是Post: import {Component} from '@angular/core';@Component({ selector: 'post',template: ` h1{{title}}/h1 p{{postText}}/p `})export class Post { title : string; postText : string; constructor(title:string,postText:string)
我有两个组件,一个是Post:
import {Component} from '@angular/core';

@Component({
    selector: 'post',template: `
    <h1>{{title}}</h1>
    <p>{{postText}}</p>
    `
})
export class Post {
    title : string;
    postText : string;
    constructor(title:string,postText:string) {
        this.title  = title;
        this.postText = postText;
    }
}

另一个是新闻源:

import {Component} from '@angular/core';
import {Post} from "./app.post.component";

@Component({
    selector: 'news-feed',template: `
    <h1>News Feed</h1>
    <ul *ngFor='#post of posts'>
        <li *ngFor='#post of posts'>
            {{post | json}}
        </li>
    </ul>
    `
})
export class NewsFeed {
   posts : Post[];
    constructor() {
        let p1 = new Post("Post1","Wow greate post");
        let p2 = new Post("Such Post","WoW");
        this.posts =[];
        this.posts.push(p1);
        this.posts.push(p2);
    }
}

有没有办法让我在帖子中使用模板重复每个帖子,而不是仅使用对象语法或格式化新闻源内的帖子.也许我正在以错误的方式接近这个,因为我是ang2的新手.任何帮助表示赞赏.

非常感谢你.

事实上,Angular2将为您实例化组件.只需在ngFor循环中添加选择器标记:
<ul>
  <li *ngFor="#postData of posts">
    <post [title]="postData.title"
          [postTest]="postData.postText"></post>
  </li>
</ul>

您的帖子数据必须以这种方式定义:

posts : any[];
constructor() {
  this.posts =[];
  this.posts.push({title:"Post1",postText:"Wow greate post"});
  this.posts.push({title:"Such Post",postText:"WoW"});
}

为此,您需要重构一下您的组件以添加输入:

@Component({
  selector: 'post',template: `
    <h1>{{title}}</h1>
    <p>{{postText}}</p>
  `
})
export class Post {
  @Input() // <-----
  title : string;
  @Input() // <-----
  postText : string;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读