在child中获取父指令

时间:2016-06-17 12:29:34

标签: angular typescript angular2-directives

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

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

并独立:

template: '<app_inp></app_inp>'

在第一种情况下,通过从父级调用函数来添加指令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
    }
  }
}

1 个答案:

答案 0 :(得分:6)

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

@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 {}
<%= simple_form_for @book, :html => { :multipart => true } do |f| %> 

  <%= f.input :category_id do %>
      <%= f.select :category_id, Category.all.map{|c| [c.name,c.id]}, :prompt => "Select a category" %> 
  <% end %>

  <%= f.file_field :book_img %> 
  <%= f.input :title, label: "Book Title" %>
  <%= f.input :description %> 
  <%= f.input :author %> 
  <%= f.button :submit %> 
<% end %>

Plunker example