【问题标题】:Directive not working outside a component指令在组件之外不起作用
【发布时间】:2016-05-21 16:39:10
【问题描述】:

我有一个 Angular 2 Directive 如下:

import { DOM } from 'angular2/src/platform/dom/dom_adapter';
import {Directive, ElementRef, Renderer} from 'angular2/core'

@Directive({
    selector: '[headerBG]',
    host: {
        '(click)': 'onClick()'
    }
})
export class HeaderBGDirective {

    constructor(private el: ElementRef, private renderer: Renderer) {   
    }
    onClick() {
        console.log(1234);
    }
}

如果我将此应用于body 元素:

<body headerBG>

它不起作用。

但是如果我把它放在另一个组件中,它就可以正常工作:

@Component({
selector: 'courses',
template: `<h2>
            {{title}}
            <input type='text' headerBG/>
          </h2>
          <ul>
              <li *ngFor="#course of courses">
              {{course}}
              </li>
          </ul>
          `,
          providers: [CourseService],
          directives: [HeaderBGDirective]
})

这是正确的行为还是我错过了什么?如何将指令应用于 body 元素而不使其成为组件?

编辑:

import {Component} from 'angular2/core';
import {HeaderComponent} from 'modules/shared/directives/header.component';
import {HeaderBGDirective} from 'modules/shared/directives/headerBG.directive';

@Component({
    selector: 'body',
    templateUrl: './welcome/templates/welcome.html',
    directives: [HeaderComponent, HeaderBGDirective]
})
export class AppComponent {
    post = {
        title: 'Favorite',
        isFavorite: true
    }
 }

在welcome.html:

<sc-header></sc-header><div>some content</div>

【问题讨论】:

    标签: typescript angular angular2-directives


    【解决方案1】:

    Angular 指令不应该在组件之外使用。 Angular2 应用程序的根是由

    实例化的组件
    bootstrap(AppComponent)
    

    其他组件和指令仅在此类根组件或该根组件的后代组件内起作用。

    【讨论】:

    • 谢谢。所以,看起来我必须在body 上启动应用程序,但这对我来说似乎是 Angular2 的一个限制点。
    • 这是否意味着我永远不能在body 标签中添加指令,因为根应用程序应该包含在某个地方(我认为应该是正文)。或者我可以这样做:` my-app中的. And then put body`?
    • 与 Angular1 相比存在一些限制。 Angular2 非常注重性能,他们不得不做出一些妥协。
    • 你可以使用'body'作为你的根组件的选择器。
    • 我使用body 作为选择器,但我不得不在template 文件中为body 移动另一个组件,现在页面加载除了我移入的组件之外。我做错了什么吗.
    【解决方案2】:

    我认为这是一个引导问题。当您引导 Angular 2 时,您指定应用程序组件

    在下面的示例中,取自https://github.com/johnpapa/angular2-tour-of-heroes/blob/master/app/main.ts,AppComponent 作为my-app 的选择器。因此,它会找到与选择器匹配的元素,并且仅限于该元素(及其后代)。

    import { bootstrap }    from 'angular2/platform/browser';
    import { AppComponent } from './app.component';
    
    bootstrap(AppComponent);
    

    因此,您的应用程序组件需要有一个 body 选择器才能正常工作。选择body 可能会出现问题,但我没有尝试确定。

    【讨论】:

      猜你喜欢
      • 2012-02-27
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      • 2021-04-20
      • 2020-10-27
      • 2019-10-22
      • 2021-10-14
      相关资源
      最近更新 更多