指令不在组件外部工作

时间:2016-05-21 16:39:11

标签: typescript angular angular2-directives

我有一个Angular 2 height如下:

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

2 个答案:

答案 0 :(得分:4)

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

实例化的组件
bootstrap(AppComponent)

其他组件和指令仅适用于此根组件的根组件或后代组件。

答案 1 :(得分:1)

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

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

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

bootstrap(AppComponent);

因此,您的应用程序组件需要有一个body的选择器才能生效。选择body时可能会出现问题,但我还没有尝试过确认。

相关问题