dellink
dellink

Reputation: 564

Get parent directive in child

I have app_form and app_input components (directives) for angular2. I can use them in template in different ways:

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

and independently:

template: '<app_inp></app_inp>'

In the first case, the directive app_inp is added by calling a function from parent, and in the second everything works as usual in angular2. Anybody know how to do it? Thank you.

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

Upvotes: 5

Views: 6182

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657486

If the type of the parent is known statically, you can just inject it

@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

Upvotes: 11

Related Questions