我有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
}
}
}
答案 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 %>