angular - 在 child 中获取父指令

标签 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 中一切正常。有人知道怎么做吗?谢谢。

更新:

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

最佳答案

如果父类的类型是静态已知的,你可以直接注入(inject)

@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

关于angular - 在 child 中获取父指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37881634/

相关文章:

typescript 不推断删除运算符和展开运算符?

typescript :使用将对象转换为其他类型。如何?还有 instanceof 或 typeof?

javascript - 如何使用模型驱动/ react 形式修改指令中的输入值

javascript - Angular 2 : property binding and side effects

angular - 测试 Angular2/Jasmine 中的选择输入更改

typescript - Angular 2 - TypeScript : how to hold objects with <Select> control

angular - 新部署 Angular2 应用程序后如何刷新浏览器

Angular2路由器导航无法正确加载组件

javascript - Material-UI 中的 DefaultTheme 导致 `Invalid module name in augmentation` 错误

javascript - Angular 5 - 如何在用户点击目标元素外部时触发事件