在child中获取父指令

del*_*ink 4 typescript angular2-directives angular

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

template: `
  <app_form>
    <app_inp></app_inp>
  </app_form>
`
Run Code Online (Sandbox Code Playgroud)

并独立:

template: '<app_inp></app_inp>'
Run Code Online (Sandbox Code Playgroud)

在第一种情况下,通过从父级调用函数来添加指令app_inp,在第二种情况下,一切都在angular2中正常工作.有谁知道怎么做?谢谢.

UPD:

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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 6

如果父级的类型是静态已知的,您可以只注入它

@Component({
  selector: 'form-cmp',
  providers: [],
  template: `
  <div>form</div>
  <ng-content></ng-content>
  `,
  directives: []
})
export class FormComponent {}
Run Code Online (Sandbox Code Playgroud)
@Component({
  selector: 'my-inp',
  providers: [],
  template: `
  <div>myInp</div>
  `,
  directives: []
})
export class MyInput {
    constructor(private form:FormComponent) {
      console.log(form);
    }
}
Run Code Online (Sandbox Code Playgroud)
@Component({
  selector: 'my-app',
  providers: [],
  template: `
  <form-cmp>
    <my-inp></my-inp>
  </form-cmp>
  `,
  directives: [FormComponent, MyInput]
})
export class App {}
Run Code Online (Sandbox Code Playgroud)

Plunker的例子

  • 当然可以:)只是在前面添加`@Optional()`https://plnkr.co/edit/elerguYGQjtFa7LBoOYx?p=preview (3认同)