【问题标题】:Angular 2 alpha 22, How to pass down a value to a component through attributes?Angular 2 alpha 22,如何通过属性将值传递给组件?
【发布时间】:2015-08-20 06:12:35
【问题描述】:

我用选择器“app”声明了一个组件 然后我像下面这样使用它:

<app title="Awesome Title"></app>

在我写的模板中:

The title passed {{ title }}

我确实添加写了组件注释:

@Component({
    selector: 'app',
    properties: {title:'title'}  // also tried ['title']
});

但是什么也没显示,输出是

The title passed

有什么帮助吗?谢谢

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    在撰写本文时,最新版本是 alpha.26。 属性定义略有变化,所以这里是新语法

    @Component({
        selector: 'app',
        properties: ['title:title']
    });
    
    <div [title]="Some Title"></div>
    

    我已经开始了一系列博客文章来演示 Angular 2 的概念。在这里查看:

    http://www.syntaxsuccess.com/viewarticle/angular-2.0-examples

    我有一个如何通过属性将属性分配给组件的工作示例。查看树视图示例,因为它大量使用它。

    【讨论】:

      【解决方案2】:

      由于某种原因,properties 似乎无法在引导的根应用上运行。

      尝试创建一个名为“title-app”的组件并将其加载到“app”中。

      // inner component
      @Component({
        selector: 'title-component',
        properties: {title:'title'}
      })
      @View({ template: '<h1>{{title}}</h1>'})
      class titleComponent{}
      
      // root app
      @Component({ selector: 'app' })
      @View({ 
        directives: titleComponent, 
        template: '<title-component [title]="Some Title"></title-component>' 
      })
      class App{}
      

      您可能还想使用最新版本的 Angular2:目前为alpha-26。从 alpha-26+ 开始,如果您的属性名称相同,则只需调用一次即可。

      properties: {'title': 'title'} => properties: 'title'

      【讨论】:

      【解决方案3】:

      正确的做法是:

      import {
        ComponentAnnotation as Component,
        ViewAnnotation as View, bootstrap
      } from 'angular2/angular2';
      import {Attribute} from 'angular2/src/core/annotations_impl/di';
      
      
      @Component({
        selector: 'app'
      })
      @View({
        template: '{{goofy}} stuff'
      })
      class App {
        goofy:string;
        constructor(@Attribute('goofy') goofy:string) {
            this.goofy = goofy;
        }
      }
      
      bootstrap(App);
      

      在此处查看完整的 Plunker http://plnkr.co/edit/n2XWez69HNJbixH3tEmR?p=preview

      但是,这目前已被破坏并且是一个已知问题https://github.com/angular/angular/issues/1858

      【讨论】:

      • 我想在@Attribute 中使用两个属性,在这种情况下假设goofy 和toffy。但这对我不起作用。有什么解决办法吗?我正在使用 angular alpha 42。属性适用于一个属性。
      • 看起来导入现在是import { Attribute } from "angular2/core"。我正在使用 alpha 47。
      猜你喜欢
      • 1970-01-01
      • 2015-11-29
      • 2017-11-29
      • 1970-01-01
      • 2016-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多