Tìm kiếm trang web

angular - Lấy directive cha trong directive con


Tôi có các thành phần (directive) app_form và app_input cho Angular2. Tôi có thể sử dụng chúng trong template theo nhiều cách khác nhau:

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

và một cách độc lập:

template: '<app_inp></app_inp>'

Trong trường hợp đầu tiên, chỉ thị app_inp được thêm bằng cách gọi một hàm từ parent, và trong trường hợp thứ hai mọi thứ hoạt động như bình thường trong angular2. Có ai biết cách làm không? Cảm ơn.

Cập nhật :

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

Câu trả lời #1

Nếu kiểu của cha mẹ được biết tĩnh, bạn chỉ cần tiêm nó

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

Ví dụ Plunker

Bài viết liên quan