【问题标题】:How are methods linked to components?方法如何与组件相关联?
【发布时间】:2016-11-01 15:04:55
【问题描述】:

我正在做一个教程,我对 Angular2 如何知道在哪个组件中调用什么方法感到困惑。这是一个例子......

以下在recipe-list.component.html

  <div class="col-xs-12">
  <ul class="list-group">
      <rb-recipe-item [recipe] = "recipe"  (click) = "onSelected(recipe)"></rb-recipe-item>
  </ul>

我了解[recipe] 属性是rb-recipe-item 组件的一部分。

(click) 调用recipe-list.component.ts 中的onSelected 方法。但是Angular2怎么知道这个方法位于recipe-list.component.ts呢?

如果我想调用位于rb-recipe-item 组件(或任何其他组件)中的方法,我该怎么做?

【问题讨论】:

  • 它知道,因为这是您在其标记中定义绑定的组件。如果您想在子组件中使用方法,请将事件绑定到子标记中最外层的元素上。如果您想在其他地方使用方法,则必须通过公共父组件显式编排它。
  • 但我将 [recipe] 属性绑定在同一个标​​记中。它是否仅仅因为我使用了方括号 [ ] 就将该属性与“rb-recipe-item”组件相关联?
  • 括号 [] 和括号 () 分别表示向内和向外绑定。 click 事件来自子组件,您将其绑定到当前组件上的方法。 recipe 正在从当前组件输入(抱歉)到子组件中。
  • 我明白了。谢谢。您的描述很有帮助。

标签: angular angular2-template


【解决方案1】:

组件与模板或模板 url 相关(如果您在单独的文件中编写 HTML)。 模板或模板 url(不要在同一个组件中同时使用),在组件元数据中定义。

@Component({
    selector: 'component-selector',
    template: // your template here
    //Which is calling the recipe
})
export class YourComponent{
   recipe(){
   // body of the method recipe
   }
}

【讨论】:

    猜你喜欢
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 2016-03-29
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多