当我在TypeScript中使用元数据注释类时,例如创建一个Angular2组件,我可以访问该类中的元数据吗?
import {Component} from 'angular2/core';
@Component({
selector: 'app',
templateUrl: '/app/components/app/app.component.html'
})
export class AppComponent {
// can I access 'templateUrl' from above annotation here?
}
Run Code Online (Sandbox Code Playgroud) 在我的情况下,我有一个组件,如果它在特定组件内,应该表现不同.所以我想通过父母来查找正确类型的组件,在简单的情况下通过依赖注入很好地工作:
子组件
@Component({
selector: 'spike-child',
template: `<div>I am the child, trying to find my parent.
<button (click)="log()">Test</button></div>`
})
export class ChildComponent {
// Get Parent through dependency injection; or null if not present.
public constructor(@Optional() private parent: ParentComponent) { }
public log(): void {
console.log('Parent', this.parent);
console.log('Parent.Id', this.parent && this.parent.id);
}
}
Run Code Online (Sandbox Code Playgroud)
父组件
@Component({
selector: 'spike-parent',
template: `
<div>
<div>I am the parent of the content below, ID = {{ id }}:</div>
<ng-content></ng-content>
</div>`
})
export class ParentComponent {
@Input() …
Run Code Online (Sandbox Code Playgroud)