在 child 中获取 parent 指令

Get parent directive in child

我有 angular2 的 app_form 和 app_input 组件(指令)。我可以用不同的方式在模板中使用它们:

template: `
  <app_form>
    <app_inp></app_inp>
  </app_form>
`

并独立:

template: '<app_inp></app_inp>'

在第一种情况下,指令 app_inp 是通过从 parent 调用函数添加的,而在第二种情况下,在 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
    }
  }
}

如果父类的类型是静态已知的,你可以直接注入它

@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 {}

Plunker example