【问题标题】:Angular2 Create a componentAngular2 创建一个组件
【发布时间】:2016-02-02 10:42:41
【问题描述】:

我想在 angular2 中创建一个具有特定属性的新组件,这样我就可以有一个标签用作这个

<my-cmp type="Type1"></my-cmp>

我尝试了许多示例,但没有一个有效。如果有人有任何工作示例,请帮助我,谢谢。

谢谢 哈立德

【问题讨论】:

    标签: javascript html typescript components angular


    【解决方案1】:

    给你。见this plunker。用 TypeScript 编写:

    import {Component, Input} from 'angular2/angular2'
    
    @Component({
      selector: 'my-cmp'
      template: `
        <div>
          <b>Type:</b> {{ type }}
        </div>
      `
    })
    class MyComponent {
      @Input() type;
    }
    
    @Component({
      selector: 'my-app',
      directives: [MyComponent],
      template: `
        <my-cmp type="Static Type"></my-cmp>
        <my-cmp [type]="dynamicType + dynamicTypeIndex"></my-cmp>
      `
    })
    export class App {
      dynamicType: string = 'Dynamic Type ';
      dynamicTypeIndex: number = 0;
    
      constructor() {
        setInterval(() => ++this.dynamicTypeIndex, 1000);
      }
    }
    

    【讨论】:

      【解决方案2】:

      你可以玩my test repository(为presentation做的我做了关于Angular 2.0的准备)

      希望对你有帮助...

      编辑

      另一个有趣的资源是我创建的playground repository,用于试验 ngUpgrade。对于当前的 Angular 2.0 版本(alpha 45),此功能尚未公开,但我通过从 Angular 的源代码中导入模块来演示它的使用。

      【讨论】:

      • 谢谢@Yaniv,这看起来很棒,我会试一试,然后再次回复你:) 干杯
      【解决方案3】:

      最简单的答案是@Component 注解将任何 typescript 类转换为 angular2 组件。任何注释为 @Component({}) 的打字稿类都是 angular2 组件。正如您在上一个答案中看到的那样,有 2 个类使用 @Component 进行了注解。 Component 将一个 json 对象作为参数告诉 angular2 组件的行为。

         @Component({
            selector: 'my-app',   //will be user in html as tag/attribut
            template: `   //the html injection etc
              <my-cmp type="Static Type"></my-cmp>
              <my-cmp [type]="dynamicType + dynamicTypeIndex"></my-cmp>
            `
          })
          export class AppCompoment {   //we exported this class/component so that it can be imported
      
          }
      

      【讨论】:

        猜你喜欢
        • 2017-04-20
        • 1970-01-01
        • 2017-07-21
        • 1970-01-01
        • 2016-11-05
        • 1970-01-01
        • 2015-08-30
        • 2017-11-01
        • 2017-04-27
        相关资源
        最近更新 更多