我有 angular2 的 app_form 和 app_input 组件(指令)。我可以用不同的方式在模板中使用它们:
template: `
<app_form>
<app_inp></app_inp>
</app_form>
`
独立地:
template: '<app_inp></app_inp>'
在第一种情况下,指令 app_inp 是通过调用父函数添加的,而在第二种情况下,在 angular2 中一切正常。有人知道怎么做吗?谢谢。
更新:
export class InputComponent {
constructor() {}
ngAfterViewInit() { // maybe ngAfterViewInit isn't the best way
if(!isHasParentForm){ // if we have parent directive app_form
// we run some logic for adding our component
} else {
// if we don't have parent like app_form we run different logic
}
}
}
最佳答案
如果父类的类型是静态已知的,你可以直接注入(inject)
@Component({
selector: 'form-cmp',
providers: [],
template: `
<div>form</div>
<ng-content></ng-content>
`,
directives: []
})
export class FormComponent {}
@Component({
selector: 'my-inp',
providers: [],
template: `
<div>myInp</div>
`,
directives: []
})
export class MyInput {
constructor(private form:FormComponent) {
console.log(form);
}
}
@Component({
selector: 'my-app',
providers: [],
template: `
<form-cmp>
<my-inp></my-inp>
</form-cmp>
`,
directives: [FormComponent, MyInput]
})
export class App {}
关于angular - 在 child 中获取父指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37881634/